My Blog for coding and note

https://github.com/hesthers

0%

EDA pt.2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
df = pd.pivot_table(data = movie_train, columns='screening_rat', index = 'genre', values= ['director'], aggfunc=len, )
df_rate = [i[1] for i in df.columns]

reset_df = pd.DataFrame(df.values, columns = sorted(movie_train.screening_rat.unique()))
reset_df.fillna(0, inplace=True)
reset_df['index'] = sorted(movie_train.genre.unique())
reset_df = reset_df.set_index(reset_df['index'], drop=True)
reset_df.drop(columns = 'index', inplace=True, axis=1)

from matplotlib import font_manager, rc
rc('font', family = 'Malgun Gothic')
plt.figure(figsize = (20 , 16))
sns.histplot(data = reset_df.T, multiple='dodge', bins = 3)
plt.xlim([0, 65])
plt.show()

plt.rcParams['axes.unicode_minus'] = False
plt.figure(figsize = (12 , 8))
sns.kdeplot(data = reset_df.T, multiple='layer')
plt.show()

image_1

image_2

Design Thinking Process

  1. 사건을 디자인하라. (Design the event/context)
  • 고급 호텔의 레스토랑의 식탁보 = 당신만을 위한 것
  • 데이터로 추출되지 않는 인사이트를 도출해내는 것.
  1. 대상과 상황을 분리하지 말아라. (Do not let objects and context separate)
  • 대상이 존재하는 컨텍스트 (상황)과 분리하여 볼 수 없음.
  • “상대방을 이해하기 위해 상황을 이해하는 것.”
  • 예. 병원과 MRI의 상황을 분리할 수 없음.
  • 상황을 잘 살펴보는 것. 대상이 맥락에서 어떤 존재인가
  1. 주관적 관점과 객관적 관점으로 바라보라. (Look somthing subjectively and objectively)

  2. 관찰하고 관찰하라 (Look at everything again and again)

  • 파괴적 혁신
  1. 아이디어를 이용해라. (Hitting on a good idea, write it all)

Design Thinking

오랜 시간 동안 디자인과 마케팅 그리고 데이터는 뗄래야 뗄 수 없는 필수불가결한 존재이다. 사실 인류가 살아오면서 디자인과 함께 존재해왔다고 해도 과언이 아니다. 고대 그리스 아니 어쩌면 그 전부터 인류가 나타나기 시작한 그 때부터가 아닐까 싶다. 인류가 살면서 인류에 최적화된 도구들을 만들고 하면서부터 디자인이 시작된 건 아닐까라는 생각을 해본다.

인류가 수없이 전쟁 등을 치루면서 생존의 문제를 겪어왔다. 그러면서 어떻게 해야 살아남을까하는 그런 생존 문제들을 해결하기 위해 어떠한 관점으로 문제를 바라왔을까 이러한 생각 또한 디자인이 아니였을까.

디자인 씽킹에서 중요하게 보는 것이 사람의 관점, 어떻게 상황과 문제를 분석하고 해결할지에 대한 것이다.

어떤 직업을 갖고 있느냐에 따라 디자인의 적용 분야와 의미가 다르다. 단순히 눈에 보이는 작품적인 면에서의 디자인은 흔하다. 눈에 보이는 것은 뻔하니까. 그러나 여기에 자신만의 가치와 쓸모있는 기능을 더하면 그것은 아주 유용한 디자인이 된다.

그러나 모든 문제들은 눈에 띄지 않는다. Invisible problem. 이걸 찾아내는 것이 의미있는 행위라 할 수 있다. 일반적으로 데이터 분석에서 인사이트를 도출한다하는 것은 데이터 자체만 가지고 바라봤을 때 눈에 보이지 않는 해석을 찾아야 한다는 것과 같은 셈이다.

우리가 일반적으로 겪는 상황들 속에서 이건 불편한 것, 이랬으면 좋겠다 싶은 것들이 꽤 있다. 그 속에서 겪는 불편함을 해소하고자 디자인을 하고 문제를 해결하기도 한다. 예를 들어보자면, 장애인을 위한 저상버스가 아닐까 생각해본다.

타인에 대한 이해. 심리학에서도 다루는 이 심리적인 부분을 이용하여 마케팅에 이용하듯 디자인에서도 이 섬세한 배려가 엿보이기도 한다.

혁신, 디자인, 가치, 욕구와 욕망.

오늘 디자인 씽킹 수업을 듣고 난 후 들었던 생각들을 한 번 정리해봤다…

TIS

  • watched the online lectures about:

how to preprocess the data effectively
with EDA introduction

how to read files that have the different types in python

indexing & masking with data structure
reading files
merge and concat
matplotlib visualization

My idea

오늘은 내가 빅데이터를 공부하면서 느꼈던 것들을 잠시 적어볼까 싶다.

사실 빅데이터를 공부하게 된 것은 아주 우연이였다. 원래는 금융분야를 전공으로 공부하고 있었는데 우연치않게 빅데이터를 접하게 되고 진로를 고민해보게 되었다. 마케팅 개론 수업때 빅데이터라는 용어를 접한게 다였고 사실 생각도 못했다. 그러나 취업을 포함해 내가 가장 관심을 가지고 열심히 해볼 수 있는 분야가 무엇일까 고민하던 중 접한 영역이 빅데이터였다. 미국 기업에 인턴 준비하려고 하던 중 자격요건으로 빅데이터 관련 스킬을 요구하는 기업들이 많아서 결국은 포기했었다.

코딩도 전혀 모르고 파이썬? R? 이런 건 대체 뭔지도 모르는 내가 이것들을 공부하면서 앞으로는 데이터는 절.대. 무시할 수 없는 중요한 분야임을 깨달았다. 코딩하면서 결과가 잘 안나오거나 오류가 계속 나면 노트북을 때로는 내려치고 싶을 때도 있지만 그래도 끝까지 해보면서 며칠이 걸려도 결과물이 나오면 뿌듯할 때도 많다.

부족하지만 그래도 코딩을 해나가다보면 얻는 인사이트들도 많다.

일상의 모든 것들이 빅데이터이다. 지금 이순간 내가 github 블로그에 코딩으로 포스팅하면서 올리는 포스트들 모두 데이터인 셈이다. 나중을 되돌아 봤을때 지금 공부해왔던 것들이 하나씩 쌓여가며 큰 도움이 되지 않을까 싶다.

쉽게 얻은 것들은 나중에 크게 대가를 치르게 된다. 그렇기 때문에 자격증도 지금 빅데이터를 공부하고 있는 모든 것들이 쉽게 얻어진 것들이 아니기에 큰 빛을 발하게 되리라 기대해본다.

TIS (Today What I studied)

Today is the most busy and exhausting day…

I watched the online lecture video about handling data, including data preprocessing, to prepare for the new project.

The lecture is about:

  • data structure: list, tuple, dictionary
  • for iteration
  • Numpy
  • Pandas: Series, Data Frame

I also practiced the machine learning to prepare for Bigdata certificate.

After preprocessing the missing values

The next step is EDA after preprocessing the missing values in DataFrame.

Figuring out the lowest correlation, then dropping the columns that are less correlated.

The following codes are for EDA.

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
movie_train.corr()
sns.heatmap(data = movie_train.corr(), annot=True)

movie_train.corr()[movie_train.corr() >= 0.3]

movie_train.drop(columns = 'num_actor', inplace=True)
sns.heatmap(data = movie_train.corr(), annot=True)

col_mt = movie_train.columns.difference(['num_staff'])
movie_train[col_mt].corr()
sns.pairplot(movie_train[col_mt])

### Title, distributor, genre, release_time, screening_rat, director
distributor = movie_train.distributor.value_counts().sort_values(ascending=True)
distributor = distributor[distributor > 2]
distributor_name = distributor.index.tolist()
distributor_cnt = distributor.values.tolist()

plt.rc('font', family = "Malgun Gothic")
fig=plt.figure(figsize = (15,10))
ax = fig.add_subplot(1,1,1)
sns.barplot(distributor_name, distributor_cnt, data = movie_train)
plt.xlabel('배급사', fontsize = 15)
plt.title('영화 배급사 수', fontsize = 20)
ax.set_xticklabels(distributor_name, rotation=75)
plt.show()
#------------------
genre = movie_train.genre.value_counts().sort_values(ascending=True)
genre = genre[genre > 1]
genre_name = genre.index.tolist()
genre_cnt = genre.values.tolist()

plt.rc('font', family = "Malgun Gothic")
fig=plt.figure(figsize = (15,10))
ax = fig.add_subplot(1,1,1)
sns.barplot(genre_name, genre_cnt, data = movie_train)
plt.xlabel('장르', fontsize = 15)
plt.title('장르별 영화 수', fontsize = 20)
ax.set_xticklabels(genre_name, rotation=75)
plt.show()
#--------------------
rate = movie_train.screening_rat.value_counts().sort_values(ascending=True)
rate = rate[rate > 1]
rate_name = rate.index.tolist()
rate_cnt = rate.values.tolist()

plt.rc('font', family = "Malgun Gothic")
fig=plt.figure(figsize = (15,10))
ax = fig.add_subplot(1,1,1)
sns.barplot(rate_name, rate_cnt, data = movie_train)
plt.xlabel('등급', fontsize = 15)
plt.title('등급별 영화 수', fontsize = 20)
ax.set_xticklabels(rate_name, rotation=75)
plt.show()
#----------------------
director = movie_train.director.value_counts().sort_values(ascending=True)
director = director[director > 1]
director_nm = director.index.tolist()
director_cnt = director.values.tolist()

plt.rc('font', family = "Malgun Gothic")
fig=plt.figure(figsize = (15,10))
ax = fig.add_subplot(1,1,1)
sns.barplot(director_nm, director_cnt, data = movie_train)
plt.xlabel('감독명', fontsize = 15)
plt.title('감독별 영화 수', fontsize = 20)
ax.set_xticklabels(director_nm, rotation=75)
plt.show()

I added the visualization codes about the nominal data.

I am not done yet!

The codes are just the first step of EDA.

This post is for a series of practice for machine learning.

I used movie data in order to practice the machine learning by preparing for the big data certificate test.

The python code below is just to preprocess the data. (Today I will post only codes of preprocessed training data.)

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
# import modules & files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder

pd.set_option('display.max_columns', 30)

movie_train = pd.read_csv('./movies_train.csv', encoding = 'utf8')

movie_train.head(2)

movie_train.info()

sns.heatmap(data = movie_train.corr(), annot=True)

movie_train.corr()[movie_train.corr() >= 0.3]

########## Figuring out missing value
movie_train[movie_train.dir_prev_bfnum.isnull()]
movie_train.dir_prev_bfnum.isnull().sum()
movie_train.isnull().sum()[movie_train.isnull().sum() <= len(movie_train) * 0.7]

movie_train.director.value_counts()

idx_dir_bfn = [n for n in movie_train['director'].values]
null_idx_dir_bfn = [movie_train[['director', 'dir_prev_bfnum']][movie_train['dir_prev_bfnum'].isnull()].values[m][0] for m in range(movie_train['dir_prev_bfnum'].isnull().sum())]
nn_idx_dir_bfn = [movie_train[['director', 'dir_prev_bfnum']][movie_train['dir_prev_bfnum'].notnull()].values[m][0] for m in range(movie_train['dir_prev_bfnum'].notnull().sum())]

len(movie_train['director'][movie_train['dir_prev_bfnum'].isnull()])
len(set(idx_dir_bfn))
len(movie_train['director'][movie_train['dir_prev_bfnum'].notnull()].unique())

dir_nm = []
for j in nn_idx_dir_bfn:
for i in null_idx_dir_bfn:
if i not in j:
pass

elif i in j:
dir_nm.append(i)

dir_nm = set(dir_nm)

bf_num = [movie_train['dir_prev_bfnum'][movie_train.director == n].values for n in dir_nm]
df = pd.DataFrame(bf_num)
df.drop(columns = [4, 5, 6], inplace=True, axis=1)
df['dir_nm'] = dir_nm
df

df.fillna(0, inplace=True)
zero_cnt = [list(df.iloc[i, 0:4].values).count(0) for i in range(0,len(df))]

tot_bfnum = []
df_mean = []
for i in range(0,len(df)):
if list(df.iloc[i, 0:4].values).count(0) == 1:
tot_bfnum = np.delete(df.iloc[i, 0:4].values, list(df.iloc[i, 0:4].values).index(0))
df_mean.append(np.mean(tot_bfnum))

elif list(df.iloc[i, 0:4].values).count(0) == 2:
tot_bfnum = np.delete(df.iloc[i, 0:4].values, list(df.iloc[i, 0:4].values).index(0))
tot_bfnum = np.delete(tot_bfnum, list(tot_bfnum).index(0))
df_mean.append(np.mean(tot_bfnum))

elif list(df.iloc[i, 0:4].values).count(0) == 3:
tot_bfnum = np.delete(df.iloc[i, 0:4].values, list(df.iloc[i, 0:4].values).index(0))
tot_bfnum = np.delete(tot_bfnum, list(tot_bfnum).index(0))
tot_bfnum = np.delete(tot_bfnum, list(tot_bfnum).index(0))
for i in list(tot_bfnum):
df_mean.append(i)

df['mean_bfnum'] = df_mean

dir_bfnum_dict = {nm : num for nm, num in zip(df['dir_nm'], df['mean_bfnum'])}

mt = pd.merge(movie_train, df[['dir_nm', 'mean_bfnum']], how = 'outer', left_on = 'director', right_on = 'dir_nm')

for n in dir_nm:
movie_train['dir_prev_bfnum'][(movie_train.director == n) & (movie_train['dir_prev_bfnum'].isnull())] = movie_train['dir_prev_bfnum'][(movie_train.director == n) & (movie_train['dir_prev_bfnum'].isnull())].apply(lambda x:dir_bfnum_dict.get(n))

movie_train.info()
movie_train.fillna(0, inplace=True)

I filled the missing values by mean of each director’s the number of previous cinema audiences.

Please do not copy codes for commercial purpose. (The copyright of data and the question owned by Dacon)

Data Preprocessing

오늘 어떤 내용을 올릴까 고민하다가 갑자기 문득 이걸 해보려고 한다. (소재가 없어서다…)

데이터 전처리!

데이터 전처리는 사실 데이터 분석에서 아주 중요한 부분이다. 전처리를 하지 않은 경우 수치상의 상관계수라던가 모델링에서 문제가 발생할 수 있어서다. 과적합 등의 문제가 발생하게 되면 예측 모델이나 분류 모델 등 성능이 떨어지기 때문이다.

이 전처리 부분을 다루는 이유는 어제 빅분기 실기시험 대비 머신러닝 연습하다가 깨달은 부분이기도 하다. 데이터 전처리에서 낑낑거렸는데 알고보니 잘못 방향을 잡아서 데이터 프레임 병합이 안되거나 상관계수가 너무 낮게 나오기도 했다.

그래서 데이터를 불러오고 처음에는 결측값 등을 먼저 확인해야한다. 그리고 결측값을 파악하고 나면 describe (파이썬) 으로 수치형 데이터들의 정보를 확인해봐야 한다. 어느 정도 정리가 되었다면 명목형 데이터 부분들을 확인하고 불필요한 컬럼들이 있는지 있다면 당연히 제거를 해야한다. 그리고 scaling을 해서 표준편차 등의 수치들에 문제가 없는지를 파악하고 전반적으로 heatmap/pairplot으로 상관관계 여부를 확인해볼 필요가 있다는 것.

만약 회귀분석으로 예측 모델링을 했다면 regression OLS와 다중공선성 코드를 통해 컬럼간의 관계나 혹은 과적합 등의 문제가 발생하고 있는지 등을 파악하고 다시 전처리 과정을 거쳐야 한다.

이 부분들을 거치지 않으면 생각한대로 결과가 나오지 않는다는 것을 파이썬을 배우면서 깨달았지만 막상 실전이라 생각하고 연습하니 잘 안되었다… 연습이 얼마나 많이 필요한지도 알게 되었고 만약 실무에서 내가 이 데이터들을 다루고 모델링을 한다고 하면 엄청난 노력이 필요하지 않을까 싶다.

Feature preprocessing과 EDA가 빅데이터 분석에서 엄청나게 중요하다는 것을 다시 한번 새삼 느껴본다.

Basic statistics

Things to know

  • the reason why the statistics is used (what I want to know from the statistical info)
    • 데이터의 의미를 정확히 모를 때(when I need more knowledge about the field)
    • 데이터 자체는 쉽게 파악이 되나 데이터 양이 많을 때 (if the volume of the info is vast, it is difficult to figure out the details)
    • 측정을 잘못 했을 때 (noise is too many in info or need the reliability)
      를 대비해서 데이터에 대해 알기 위해 사용
  • the tendency of covariance
    • the degree that two variances are distant from each mean value => as another one is moving forward the postive/negative direction being distant from its mean, one variance is also moving forward the positive direction being distant from its mean.
    • When the deviation is multiplied, the output value is also larger. But, when the unit is different from each data, the scale of the deviation is also different. In other words, you cannot compare with these data, so you need to standardize the data first.
  • correlation coefficient
    • You cannot explain anything (e.g. the relation) only using the correlation coefficient.
    • Correlation coefficient cannot describe the nonlinear relation. (You have to identify if there are direct correlation among the data first.)
    • Because raw data originally includes the noise, you cannot figure out the perfect linear relation. In linear regressional coefficient, the errors are included.)
  • the basic concepts of the sample compared to the population
    • data should be unbiased. (if the specific biased information is identified from the sample, this information cannot explain about the population.)
    • the features of the sample are same as of the population (you cannot predict at all if they are totally different.)

Statistics

concepts

  1. central tendency
  • mean(average): dividing the sum of data by the count of the data
  • median: 50% of a quantile or the data in the middle of the whole data
  • mode: the frequent count of data
  • quantile: 25%, 50%, 75% of the whole data
  1. measurement of distribution
  • variance: how widely the whole data distribute
  • std(standard deviation): the square root of variance
  1. coefficient
  • correlation coefficient: the size of the relation between two variances / range must be within [-1, 1].
    the degree of the change to one variance as another one also changes
  • covariance: the degree of how far both two variances are distant from each mean value / when one variance is in faraway point from its mean, how far another variance is distant from its mean
  1. regression
  • Linear regression => regressional coefficient (the size that the independent variance impacts the dependent variance)

    important: minimizing the errors of data

  • for the prediction

Sometimes, everyone needs some breaktime. When you have in trouble, you might want to give up everything, but I think everyday is beautiful!

You deserve to be loved.

Anne-Marie Beautiful

你敢有勇气,别放弃自己。你可以爱自己,能让自身够珍贵吧。

Cosine distance

png image

  • The relationship between cosine similarity and distance

This is test image for this blog post.
I wrote things on this file, so the original copyright to me.

data with algebra

Vector

  • 3 terminology consisting of Vector
  1. basis means axis
  2. dimension means the amount of the feature (columns of a table)
  3. direction is related to unit vector (this literally means unit)
  • direction is about physical trend.

  • distance between vectors

  1. Euclidean distance: the sum of the absolute difference between two vectors
  2. Manhattan distance: the square root of the sum of the squared difference between two vectors
  3. Cosine distance: the multiplication of the two vectors divided by the sum of the scalar product of each vector

    cosine distance is related to cosine similarity.