Repository navigation
Expand file tree
/
Copy pathMachine_Learning_00.Rmd
More file actions
499 lines (387 loc) · 17.5 KB
/
Copy pathMachine_Learning_00.Rmd
File metadata and controls
499 lines (387 loc) · 17.5 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
---
jupyter:
jupytext:
formats: ipynb,Rmd
text_representation:
extension: .Rmd
format_name: rmarkdown
format_version: '1.0'
jupytext_version: 1.0.5
kernelspec:
display_name: Python 3
language: python
name: python3
---
```{python}
# %autosave 0
```
```{python}
import pandas as pd
import numpy as np
import os as os
import matplotlib.pyplot as plt
import re
import nltk
```
# Assignment 1 - Machine Learning 184.702 SS 2019
### 26.03.2019 Group06
| Name | Matrnr. |
|------|---------|
| Josef Weber | 01363254|
|Ziegelbecker Thomas | 0925321|
|Pintaric Thomas | 1111111|
## Data Set 1: Twitter sentiment140
### Explanation
This is the sentiment140 dataset. It contains extracted tweets using the twitter api. The tweets have been annotated and can be used to detect sentiment. <sup>1</sup>
We chose this dataset because we are interested in doing text analysis and since this dataset has a very limited amount of features, while having lots of samples.
Dataset Source <sup>1</sup> [twitter dataset](https://www.kaggle.com/kazanova/sentiment140)
### Characteristics
#### How many samples:
Dataset has 1.600.000 tweets (samples) and 9 columns, one of them being the feature.
#### How many attributes (features):
The aim is to extract features by taking the tweet text from each datapoint and splitting the single whole text into words to classify them, weather they have positive or negative meaning. Using dictionaries that contain words which represent specific emotions we decide if a tweet is positive, negative or neutral.
<br>
So far we cleaned the tweets by applying some regex to handle URL's, references to other twitter-users, additional whitespace, turning the text into lowercase and more to prepare for further analysis.
<br>
Based on the method, tool and dictionary that we will use in the future we will end up having a fairly large amount of columns (features) each representing the quantity of a word that is contained in each tweet. If the positive amount of words will dominate then the tweet will be labeled with a positive sentiment.
### Which data types:
* target: the polarity of the tweet (0 = negative, 2 = neutral, 4 = positive) [dtype = int64]
* nominal
* ids: The id of the tweet (2087) [dtype = int64]
* ordinal
* date: the date of the tweet (Sat May 16 23:58:44 UTC 2009) [dtype = datetime]
* ordinal
* flag: The query (lyx). If there is no query, then this value is NO_QUERY. [dtype = object]
* nominal
* user: the user that tweeted (max) [dtype = object]
* nominal
* text: the text of the tweet (this is a sample tweet) [dtype = object]
* nominal
```{python}
dataset_path = 'datasets/sentiment/part-1-training.1600000.processed.noemoticon.csv.csv'
DATASET_COLUMNS = ["target", "ids", "date", "flag", "user", "text"]
#df_raw = pd.read_csv(dataset_path, encoding ='latin_1' , names=DATASET_COLUMNS)
#df_raw.head()
```
```{python}
def export_to_csv(df, file_name):
print('write file to: ', file_name)
df.to_csv(file_name, encoding='utf-8', index=False)
def clean_date(df):
'''
weekday extraction 1min
'''
def funcapply(x):
return x[0:3]
df['weekday'] = df['date'].apply(lambda x: funcapply(x))
'''
parse time to pandas datetime takes 5 minutes
from datetime import datetime
d = datetime.strptime('Thu Apr 23 13:38:19 +0000 2009','%a %b %d %H:%M:%S %z %Y').strftime('%Y-%m-%d %H:%M:%S');
'''
df['date'] = pd.to_datetime(df['date'])
return df
def preprocess_tweet(tweet):
#convert the tweet to lower case
tweet = tweet.lower()
#convert all urls to string "URL"
tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))','URL',tweet)
#convert all @username to "AT_USER"
#tweet = re.sub('@[^\s]+','AT_USER', tweet)
#correct all multiple white spaces to a single white space
tweet = re.sub('[\s]+', ' ', tweet)
#convert "#topic" to just "topic"
tweet = re.sub(r'#([^\s]+)', r'\1', tweet)
return tweet
def preprocess(df):
'''
call all other functions
create new columns
'''
print("clean date...")
# split and clean date
df_new = clean_date(df)
print("clean text...")
# clean tweet text
df_new['text'] = df_new['text'].apply(preprocess_tweet)
print("add wc...")
# add col text wordcount
df_new['text_wc'] = [len(nltk.word_tokenize(t)) for t in df_new.text]
print("add len...")
# add col text string length
df_new['text_len'] = [len(t) for t in df_new.text]
return df_new
#df_clean = preprocess(df_raw)
#dataset_path = 'datasets/sentiment/sentiment140_date_clean.csv'
#export_to_csv(df_clean, './data/sentiment140_date_clean.csv')
```
```{python}
dataset_path = 'datasets/sentiment/sentiment140_date_clean.csv'
df_clean = pd.read_csv(dataset_path, encoding='utf-8', header=0)
df_clean['date'] = pd.to_datetime(df_clean['date'])
```
## Sentiment Distribution
The plot below shows clearly that half of the datasets tweets are labeled positive and half negative.
```{python}
# @hidden_cell
target_cnt = df_clean.target.value_counts()
target_cnt = target_cnt.to_frame()
target_cnt.reset_index(inplace=True)
target_cnt.columns = ['SENTIMENT', 'COUNT']
target_cnt.SENTIMENT = target_cnt.SENTIMENT.map({4:'pos', 2:'neu', 0:'neg'})
plt.figure(figsize=(5,4))
plt.bar(target_cnt.SENTIMENT, target_cnt.COUNT)
plt.title("distribution of sentiment labels")
plt.xlabel("sentiment")
plt.ylabel("count")
plt.show()
```
## Distribution of tweets by days & Distribution of tweets by Weekdays
To show how the tweets are distributed according to their appearence in time we visualized tweets by the days of the month and of the week. Therefore we had to seperate the twitter timestamp into two different columns to be comfortable to process.
```{python}
g = df_clean.groupby(by=df_clean.date.dt.day).agg('count')
df_time_plot = pd.DataFrame({"day":g.index, "count":g.ids})
plt.rcParams["figure.figsize"] = (18,5)
ax = df_time_plot.plot.bar(x='day', y='count', rot=0)
plt.xlabel("monthday")
plt.ylabel("count")
plt.title("Distribution of tweets per Month days")
plt.show()
```
```{python}
g = df_clean.groupby(by=df_clean.weekday).agg('count')
df_weekday_plot = pd.DataFrame({"day":g.index, "count":g.ids})
cats = ['Mon','Tue','Wed','Thu','Fri','Sat', 'Sun']
df_weekday_plot.day = pd.Categorical(df_weekday_plot.day,
categories=cats,
ordered=True)
df_weekday_plot.sort_values('day', inplace=True)
df_weekday_plot
plt.rcParams["figure.figsize"] = (18,5)
ax = df_weekday_plot.plot.bar(x='day', y='count', rot=0)
plt.xlabel("weekday")
plt.ylabel("count")
plt.title("Distribution of tweets per Week days")
plt.show()
```
## Distribution of text string length & text wordcount
Beside having the text as a feature vector we derived the wordcount as well as the tweet-string-length as another potential feature from the text column. It is also very handy to briefly introcude and visualize the text column. The two plots below show the how the **wordcount per tweet** and the **tweet-string-length** per tweet are distributed across the dataset. To further visualize the few outliers we introduced the box plot diagram at the right.
```{python}
plt.figure(1)
plt.figure(figsize=(15, 10))
plt.subplot(221)
plt.hist(df_clean.text_len, bins=400)
plt.title("distribution of tweet-string-length")
plt.xlabel("length")
plt.ylabel("count")
plt.subplot(222)
green_diamond = dict(markerfacecolor='b', marker='D')
plt.boxplot(df_clean.text_len, flierprops=green_diamond)
plt.title("distribution of tweet-string-length [boxplot]")
plt.ylabel("count")
###
plt.subplot(223)
plt.hist(df_clean.text_wc, bins=300)
plt.xlabel("length")
plt.ylabel("count")
plt.title("distribution of words per tweet (wordcount)")
plt.subplot(224)
green_diamond = dict(markerfacecolor='b', marker='D')
plt.boxplot(df_clean.text_wc, flierprops=green_diamond)
plt.title("distribution of words per tweet (wordcount) [boxplot]")
plt.ylabel("count")
plt.show()
```
## Data Set 2: OPPORTUNITY Activity Recognition Dataset
### Explanation
"The OPPORTUNITY Dataset for Human Activity Recognition from Wearable, Object, and Ambient Sensors is a dataset devised to benchmark human activity recognition algorithms (classification, automatic data segmentation, sensor fusion, feature extraction, etc). <sup>1</sup>
We chose this dataset for its high dimensionality, for its different nature (sensor data vs. textual data) and because it's interesting to work with sensor data.
Dataset Source <sup>1</sup> [twitter dataset](https://archive.ics.uci.edu/ml/datasets/OPPORTUNITY+Activity+Recognition#)
### Characteristics
#### How many samples:
Notes regarding the recordings of the dataset:
* 4 users each 6 runs,
* of these5 are **Activity of Daily Living (644.635 samples)** runs characterized by a natural execution of daily activities, where samples per user break down the following way:
* The 6th run is a **"drill" (118.975 samples)** run, where users execute a scripted sequence of activities. Samples per user break down the following way:
#### How many attributes (features):
The dataset comprises the readings of motion sensors recorded while users executed typical daily activities.The attributes correspond to raw sensor readings. There is a total of 242 attributes (all of type float).
* **Body-worn sensors (145 attributes):** The body-worn sensors include 7 inertial measurement units and 12 3D acceleration sensors.The inertial measurement units provide readings of: 3D acceleration, 3D rate of turn, 3D magnetic field, and orientation of the sensor with respect to a world coordinate system in quaternions.
* **Object sensors (60 attributes):** 12 objects are instrumented with wireless sensors measuring 3D acceleration and 2D rate of turn.
* **Ambient sensors (37 attributes):** Ambient sensors include 13 switches and 8 3D acceleration sensors in drawers, kitchen appliances and doors.
#### What types of attributes (nominal, ordinal, interval, ...):
Columns:
* 1 - milliseconds - duration **(ratio)**
* 2-37 - Accelerometers with the unit: milli g **(interval)**
* 38-134 - InertialMeasurementUnit withe the unit millig g and mm/s **(interval and ratio)**
* 135-194 - Accelerometers - milli g **(interval)**
* 195 - 207 - Logical binary values - on/off 0/1 **(nominal)**
* 208-231 - Accelerometer - milli g **(interval)**
* 232 - 242 - LOCATION - millimeters **(ratio)**
* 243-250 - Legend one-hot-encoded locomotion information - yes/no **(nominal)**
```{python colab={'base_uri': 'https://localhost:8080/', 'height': 8704}, colab_type=code, id=FUoaE5eIXrTd, outputId=45a93522-3153-4e11-de37-e2d5f7a99ea8}
# build the data dictionary
opportunity_cols = dict()
opportunity_cols_txt = open("datasets/opportunity/column_names.txt", "r")
for line in opportunity_cols_txt:
if re.search('Column',line) != None:
col_id = re.search('Column: (\S*) ',line).group(1)
opportunity_cols[col_id] = dict()
opportunity_cols[col_id]['name'] = re.search('Column: \S* (\S*)',line).group(1)
if re.search('Column: \S* \S* \S*',line) != None:
opportunity_cols[col_id]['sensor'] = re.search('Column: \S* \S* (\S*)',line).group(1)
opportunity_cols[col_id]['sensor_axis'] = re.search(' (\S*);',line).group(1)
opportunity_cols[col_id]['value_type'] = re.search('value = (.*),',line).group(1)
opportunity_cols[col_id]['unit'] = re.search('unit =(.*)$',line).group(1)
#opportunity_cols
# and generate the column names for the data frame
col_names = list()
for key, column in opportunity_cols.items():
col_names.append(key+"_"+column.get('name'))
col_names.insert(0,'0_User')
#col_names
```
```{python colab={'base_uri': 'https://localhost:8080/', 'height': 71}, colab_type=code, id=oqO1Zom-S0Qs, outputId=71f8505a-ca31-4b7a-fb03-1c2880a8a280}
adl_filename_mask = 'S{}-ADL{}.dat'
drill_filename_mask = 'S{}-Drill.dat'
df_opportunity_adl = pd.DataFrame()
df_opportunity_drill = pd.DataFrame()
# go through the data fractions for the 4 users
for user_idx in range(1,5):
# go through 5 adl runs and read in fractions
for run in range (1,6):
path = 'datasets/opportunity/'+adl_filename_mask.format(user_idx, run)
df_partial_adl = pd.read_csv(path, header=None, sep='\s')
df_partial_adl.insert(0,'User',user_idx)
df_opportunity_adl = df_opportunity_adl.append(df_partial_adl)
# also add the 6th "drill" run to the dataframe
path = 'datasets/opportunity/'+adl_filename_mask.format(user_idx, run)
df_partial_drill = pd.read_csv(path, header=None, sep='\s')
df_partial_drill.insert(0,'User',user_idx)
df_opportunity_drill = df_opportunity_drill.append(df_partial_adl)
#print(df_opportunity_adl.shape)
#df_adl = pd.read_csv('drive/My Drive/University/Data Science/Machine Learning/datasets/opportunity/S1-ADL1.dat', encoding='latin_1', header=None, sep='\s')
```
```{python}
# in order to not always do the read in of the fractions
#export_to_csv(df_opportunity_adl, "datasets/opportunity/opportunity_adl.csv")
#export_to_csv(df_opportunity_drill, "datasets/opportunity/oppportunity_drill.csv")
```
```{python}
# already read in from the prejoined fractions
df_opportunity_adl = pd.read_csv('datasets/opportunity/opportunity_adl.csv')
df_opportunity_drill = pd.read_csv('datasets/opportunity/opportunity_drill.csv')
#print(df_opportunity_adl.shape)
#print(df_opportunity_drill.shape)
```
```{python}
# set column names according to data dictionary
df_opportunity_adl.columns = col_names
df_opportunity_drill.columns = col_names
```
```{python}
# get sample sizes for the two types of runs per user
print("ADL:")
print(df_opportunity_adl['0_User'].value_counts())
print("\nDrill")
print(df_opportunity_drill['0_User'].value_counts())
```
```{python}
df_opportunity_adl.dtypes.value_counts()
```
```{python colab={'base_uri': 'https://localhost:8080/', 'height': 388}, colab_type=code, id=KIXW9NALTHHf, outputId=5bee476f-9eb9-4c0d-a859-97a1e8e75814}
df_opportunity_adl.head(10)
```
```{python}
df_opportunity_adl.describe()
```
### Distributions
#### Missing values:
* e.g. by looking at data distributions and percentiles which showed that certain columns (particularly the legend columns at the end) do have certain percentiles or quantiles with 0.0 meaning that there are no occurences which are a hint for missing values in the first place
* another approach is by using isnull() per column and sum per axis = 0 (columns) using pandas
which shows that a few Accelerometer columsn have a higher number of missing values ranging between 9 and 40%:
* 16_Accelerometer 21.553592
* 14_Accelerometer 21.553592
* 15_Accelerometer 21.553592
* 37_Accelerometer 44.244262
* 35_Accelerometer 44.244262
* 36_Accelerometer 44.244262
```{python}
df_opportunity_adl['248_LL_Right_Arm'].describe()
```
```{python}
missing_values_per_column = df_opportunity_adl.isnull().sum(axis=0)
x_columns = list(missing_values_per_column)
label_columns = list(missing_values_per_column.keys())
plt.hist(x_columns, 50,label=label_columns)
```
```{python}
mask = missing_values_per_column > 0
num_of_rows = df_opportunity_adl.shape[0]
missing_per_column = (missing_values_per_column[mask]/num_of_rows) * 100
missing_per_column.sort_values(inplace=True)
missing_per_column
```
```{python}
df_cleaned_opportunity_adl = df_opportunity_adl.copy().fillna(0)
```
```{python}
#print(opportunity_cols.get('240'))
```
#### A few representative distributions of the different sensor types
```{python}
plt.figure(1)
#plt.figure(figsize=(15, 10))
plt.subplot(221)
plt.hist(df_cleaned_opportunity_adl['2_Accelerometer'], bins=400)
plt.title("distribution of accelerometer 1")
plt.xlabel("millig g")
plt.ylabel("count")
plt.subplot(222)
green_diamond = dict(markerfacecolor='b', marker='D')
plt.boxplot(df_cleaned_opportunity_adl['2_Accelerometer'], flierprops=green_diamond)
plt.title("distribution of accelerometer 1 [boxplot]")
plt.ylabel("milli g")
###
plt.subplot(223)
plt.hist(df_cleaned_opportunity_adl['195_REED'])
plt.title("distribution of 195_REED")
plt.xlabel("logical (on/off)")
plt.ylabel("count")
plt.subplot(224)
plt.boxplot(df_cleaned_opportunity_adl['195_REED'], flierprops=green_diamond)
plt.title("distribution of 195_REED [boxplot]")
plt.ylabel("logical (on/off)")
plt.show()
```
```{python}
plt.figure(2)
#plt.figure(figsize=(15, 10))
plt.subplot(221)
plt.hist(df_cleaned_opportunity_adl['125_InertialMeasurementUnit'], bins=400)
plt.title("distribution of 125_InertialMeasurementUnit")
plt.xlabel("milli g")
plt.ylabel("count")
plt.subplot(222)
green_diamond = dict(markerfacecolor='b', marker='D')
plt.boxplot(df_cleaned_opportunity_adl['125_InertialMeasurementUnit'], flierprops=green_diamond)
plt.title("distribution of 125_InertialMeasurementUnit [boxplot]")
plt.ylabel("millig g")
plt.show()
```
```{python}
plt.figure(2)
#plt.figure(figsize=(15, 10))
plt.subplot(221)
plt.hist(df_cleaned_opportunity_adl['240_LOCATION'], bins=400)
plt.title("distribution of 240_LOCATION")
plt.xlabel("location mm")
plt.ylabel("count")
plt.subplot(222)
green_diamond = dict(markerfacecolor='b', marker='D')
plt.boxplot(df_cleaned_opportunity_adl['240_LOCATION'], flierprops=green_diamond)
plt.title("distribution of 240_LOCATION [boxplot]")
plt.ylabel("location mm")
plt.show()
```
* One can clearly see that as state in the description of the data that the quality of measurement regarding the accelerometer measurements are of good quality, while others such as the reed sensors only vaguely captured observations
* the different columns that were checked, irrespective of its type, seem to be normal distributed