[ UDF of connecting to Postgresql, GPDB & Getting query result as a DataFrame ]
defpostgresql_query(query):
importpsycopg2aspg importpandasaspd
# Postgresql, Greenplum DB Connect connection_string = "postgresql://{user}:{password}@{host}/{db}".\ format(user='gpadmin', # put your info password='changeme', host='localhost', db='gpadmin')
conn =pg.connect(connection_string)
cursor =conn.cursor()
#conn.autocommit = True
# execute a query and get it as a pandas' DataFrame cursor.execute(query) col_names = [desc[0]fordescincursor.description] result =pd.DataFrame(cursor.fetchall(), columns=col_names)
cursor.close()
conn.close()
returnresult
아래는 Query를 실행해서 결과를 가져오는 간단한 예시입니다.
query = """ SELECT * FROM mytable WHERE grp == 'A' LIMIT 100;
# execute a query and get it as a pandas' DataFrame cursor.execute(query) col_names = [desc[0] for desc in cursor.description] result = pd.DataFrame(cursor.fetchall(), columns=col_names)
cursor.close()
cnx.close()
return result
위에서 정의한 사용자 정의함수를 사용하여 MySQL DB에 접속하고, Query로 조회한 결과를 result 라는 이름의 DataFrame으로 저장하는 예시입니다.
query = """
SELECT * FROM mydb WHERE age >= 20 ORDER BY age;
"""
result = mysql_query(query)
(3) Python으로 IBM DB2 DB connect 하고 Query 결과 가져오는 방법
먼저, 명령 프롬프트 창에서 ibm_db_dbi 라이브러리를 설치해줍니다.
$ pip install ibm_db_dbi
다음으로 DB2에 접속해서 Query를 실행하고, 결과를 pandas DataFrame으로 가져오는 사용자 정의함수를 정의합니다.
cursor.execute(query) col_names = [ desc[0]fordescincursor.description ] result =pd.DataFrame(cursor.fetchall(), columns=col_names)
cursor.close() returnresult
Python에서 위의 사용자 정의 함수를 사용하여 query를 실행시키고 결과를 DataFrame으로 가져오는 예제입니다.
query = """
WITH
t1 AS (SELECT a, MAX(b) AS b FROM x GROUP BY a),
t2 AS (SELECT a, AVG(d) AS d FROM y GROUP BY a)
SELECT t1.*, t2.* FROM t1 JOIN t2 ON t1.a = t2.a;
"""
result = presto_query(query)
혹시 pip install 하는 단계에서 'error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/' 와 같은 에러가 나면 안내에 나와있는 사이트에 가서 Microsoft Visual C++ 을 다운받아 설치하시기 바랍니다.
이번 포스팅에서는 Python pandas 의 DataFrame에서 문자열(string)을 데이터 형태로 가지는 칼럼을 특정 기준(separator, delimiter) 분할(split a string)하여, 그 중의 일부분을 가져다가 DataFrame에 새로운 칼럼으로 만들어서 붙이는 2가지 방법을 소개하겠습니다.
(1) Vectorization을 이용한 pandas DataFrame 문자열 칼럼 분할하기
(2) For Loop operation을 통한 pandas DataFrame 문자열 칼럼 분할하기
Python pandas DataFrame: Split string column and make a new column using part of it.
(1) Vectorization을 이용한 pandas DataFrame 문자열 칼럼 분할하기 (빠름 ^^)
예제로 사용할 문자열 'id' 와 숫자형 'val' 의 두 개 칼럼으로 이루어진 DataFrame을 만들어보겠습니다. 그리고 문자열 'id' 칼럼을 구분자(separator) '_' 를 기준으로 str.split('_') 메소드를 사용하여 분할(split) 한 후에, 앞부분([0])을 가져다가 'grp'라는 칼럼을 추가하여 만들어보겠습니다.
(2) For Loop operation을 통한 pandas DataFrame 문자열 칼럼 분할하기 (느림 -_-;;;)
두번째는 For Loop 연산을 사용하여 한 행, 한 행씩(row by row) 분할하고, 앞 부분 가져다가 'grp' 칼럼에 채워넣고... 를 반복하는 방법입니다. 위의 (1)번의 한꺼번에 처리하는 vectorization 대비 (2)번의 for loop은 시간이 상대적으로 많이 걸립니다. 데이터셋이 작으면 티가 잘 안나는데요, 수백~수천만건이 되는 자료에서 하면 느린 티가 많이 납니다.
텍스트 분석을 할 때 제일 처음 하는 일이 문서, 텍스트를 분석에 적합한 형태로 전처리 하는 일입니다.
이번 포스팅에서는 (1) 텍스트 데이터를 Python의 string methods 를 이용하여 단어 단위로 파싱(parsing text at word-level) 한 후에, 단어별 index를 만들고, (2) 텍스트를 단어 단위로 one-hot encoding 을 해보겠습니다.
one-hot encoding of text at a word-level
1. 텍스트 데이터를 Python string methods를 사용하여 단어 단위로 파싱하고, 단어별 token index 만들기
# import modules
import numpy as np
import os
# set directory
base_dir = '/Users/ihongdon/Documents/Python/dataset'
file_name = 'python_wikipedia.txt'
path = os.path.join(base_dir, file_name)
# open file and print it as an example
file_opened = open(path)
for line in file_opened.readlines():
print(line)
Python programming language, from wikipedia
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aims to help programmers write clear, logical code for small and large-scale projects.[26]
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is often described as a "batteries included" language due to its comprehensive standard library.[27]
Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released 2000, introduced features like list comprehensions and a garbage collection system capable of collecting reference cycles. Python 3.0, released 2008, was a major revision of the language that is not completely backward-compatible, and much Python 2 code does not run unmodified on Python 3. Due to concern about the amount of code written for Python 2, support for Python 2.7 (the last release in the 2.x series) was extended to 2020. Language developer Guido van Rossum shouldered sole responsibility for the project until July 2018 but now shares his leadership as a member of a five-person steering council.[28][29][30]
Python interpreters are available for many operating systems. A global community of programmers develops and maintains CPython, an open source[31] reference implementation. A non-profit organization, the Python Software Foundation, manages and directs resources for Python and CPython development.
아래는 Python string method를 사용해서 텍스트에서 단어를 파싱하고 전처리할 수 있는 사용자 정의 함수 예시입니다. 가령, 대문자를 소문자로 바꾸기, stop words 제거하기, 기호 제거하기, 숫자 제거하기 등을 차례대로 적용할 수 있는 기본적인 예시입니다. (이 역시 텍스트 분석용 Python module 에 잘 정의된 함수들 사용하면 되긴 합니다. ^^;)
# UDF of word preprocessing
def word_preprocess(word):
# lower case
word = word.lower()
# remove stop-words
stop_words = ['a', 'an', 'the', 'in', 'with', 'to', 'for', 'from', 'of', 'at', 'on',
'until', 'by', 'and', 'but', 'is', 'are', 'was', 'were', 'it', 'that', 'this',
'my', 'his', 'her', 'our', 'as', 'not'] # make your own list
for stop_word in stop_words:
if word != stop_word:
word = word
else:
word = ''
# remove symbols such as comma, period, etc.
symbols = [',', '.', ':', '-', '+', '/', '*', '&', '%', '[', ']', '(', ')'] # make your own list
for symbol in symbols:
word = word.replace(symbol, '')
# remove numbers
if word.isnumeric():
word = ''
return word
다음으로, python_wikipedia.txt 파일을 열어서(open) 각 줄 단위로 읽고(readlines), 좌우 공백을 제거(strip)한 후에, 단어 단위로 분할(split) 하여, 위에서 정의한 word_preprocess() 사용자 정의 함수를 적용하여 전처리를 한 후, token_idx 사전에 단어를 Key로, Index를 Value로 저장합니다.
# blank dictionary to store
token_idx = {}
# opening the file
file_opened = open(path)
# catching words and storing the index at token_idx dictionary
for line in file_opened.readlines():
# strip leading and trailing edge spaces
line = line.strip()
# split the line into word with a space delimiter
for word in line.split():
word = word_preprocess(word) # UDF defined above
# put word into token_index
if word not in token_idx:
if word != '':
token_idx[word] = len(token_idx) + 1
단어를 Key, Index를 Value로 해서 생성된 token_idx Dictionary는 아래와 같습니다.
총 123개의 단어가 있으며, 이 중에서 'python'이라는 단어는 token_idx에 '1' 번으로 등록이 되어있습니다.
max(token_idx.values())
123
token_idx.get('python')
1
2. 텍스트를 단어 단위로 One-hot encoding 하기
하나의 텍스트 문장에서 고려할 단어의 최대 개수로 max_len = 40 을 설정하였습니다. (한 문장에서 41번째 부터 나오는 단어는 무시함). 그리고 One-hot encoding 한 결과를 저장할 빈 one_hot_encoded 다차원 배열을 np.zeros() 로 만들어두었습니다.
# consider only the first max_length words in texts
max_len = 40
# array to store the one_hot_encoded results
file_opened = open(path)
one_hot_encoded = np.zeros(shape=(len(file_opened.readlines()),
max_len,
max(token_idx.values())+1))
one_hot_encoded 는 (5, 40, 124) 의 다차원 배열입니다. 5개의 텍스트 문장으로 되어 있고, 40개의 최대 단어 길이(max_len) 만을 고려하며, 총 124개의 token index 에 대해서 해당 단어가 있으면 '1', 없으면 '0'으로 one-hot encoding을 하게 된다는 뜻입니다.
one_hot_encoded.shape
(5, 40, 124)
아래는 파일을 열고 텍스트를 줄 별로 읽어 들인 후에, for loop 을 돌면서 각 줄에서 단어를 분할하고 전처리하여, token_idx.get(word) 를 사용해서 해당 단어(word)의 token index를 가져온 후, 해당 텍스트(i), 단어(j), token index(idx)에 '1'을 입력하여 one_hot_encoded 다차원 배열을 업데이트 합니다.
file_opened = open(path)
for i, line in enumerate(file_opened.readlines()):
# strip leading and trailing edge spaces
line = line.strip()
for j, word in list(enumerate(line.split()))[:max_len]:
# preprocess the word
word = word_preprocess(word)
# put word into token_index
if word != '':
idx = token_idx.get(word)
one_hot_encoded[i, j, idx] = 1.
이해를 돕기 위하여 python_wikipedia.txt 파일의 첫번째 줄의, 앞에서 부터 40개 단어까지의 단어 중에서, token_idx 의 1번~10번 까지만 one-hot encoding이 어떻게 되었나를 단어와 token_idx 까지 설명을 추가하여 프린트해보았습니다. (말로 설명하려니 어렵네요. ㅜ_ㅜ)
# sort token_idx dictionary by value
import operator
sorted_token_idx = sorted(token_idx.items(), key=operator.itemgetter(1))
# print out 10 words & token_idx of 1st text's 40 words as an example
for i in range(10):
print('word & token_idx:', sorted_token_idx[i])
print(one_hot_encoded[0, :, i+1])
이번 포스팅에서는 (1) text 또는 csv 포맷으로 저장된 텍스트 파일을 Python의 string methods 를 사용하여 파일을 열어서 파싱하여 matrix 로 저장하고, (2) 숫자형 데이터를 표준화(standardization) 혹은 정규화(normalization) 하는 사용자 정의함수를 만들어보겠습니다.
예제로 사용할 text 파일은 전복의 성별과 length, diameter, height, whole_weight, shucked_weight, viscera_weight, shell_weight, rings 를 측정한 abalone.txt 파일 입니다.
1. text 파일을 읽어서 숫자형 값으로 만든 matrix, 라벨을 저장한 vector를 만들기
물론, Pandas 모듈의 read_csv() 함수를 이용하여 편리하게 text, csv 포맷의 파일을 읽어올 수 있습니다.
# importing modules
import numpy as np
import pandas as pd
import os
# setting directory
base_dir = '/Users/ihongdon/Documents/Python'
work_dir = 'dataset'
path = os.path.join(base_dir, work_dir)
# reading text file using pandas read_csv() function
df = pd.read_csv(os.path.join(path, 'abalone.txt'),
sep=',',
names=['sex', 'length', 'diameter', 'height', 'whole_weight',
'shucked_weight', 'viscera_weight', 'shell_weight', 'rings'],
header=None)
# check first 5 lines
df.head()
sex length diameter height whole_weight shucked_weight viscera_weight shell_weight rings
0 M 0.455 0.365 0.095 0.5140 0.2245 0.1010 0.150 15
1 M 0.350 0.265 0.090 0.2255 0.0995 0.0485 0.070 7
2 F 0.530 0.420 0.135 0.6770 0.2565 0.1415 0.210 9
3 M 0.440 0.365 0.125 0.5160 0.2155 0.1140 0.155 10
4 I 0.330 0.255 0.080 0.2050 0.0895 0.0395 0.055 7
위의 Pandas 의 함수 말고, 아래에는 Python의 string methods 를 사용해서 파일을 열고, 파싱하는 간단한 사용자 정의함수를 직접 만들어보았습니다.
위의 abalone.txt 파일의 데이터 형태를 참고해서 파일 이름, 숫자형 변수의 개수, 숫자형 변수의 시작 위치, 숫자형 변수의 끝나는 위치, 라벨 변수의 우치를 인자로 받는 사용자 정의함수를 정의하였습니다. 분석을 하려는 각 데이터셋에 맞게 인자와 함수 code block 을 수정하면 좀더 유연하고 데이터 특성에 적합하게 파일을 불어올 수 있는 사용자 정의함수를 만들 수 있습니다.
def file2matrix(filename, val_col_num, val_col_st_idx, val_col_end_idx, label_idx):
"""
- filename: directory and file name
- val_col_num: the number of columns which contains numeric values
- val_col_st_idx: the index of starting column which contains numeric values
- val_col_end_idx: the index of ending column which contains numeric values
- label_idx: the index of label column
"""
# open file
file_opened = open(filename)
lines_num = len(file_opened.readlines())
# blank matrix and vector to store
matrix_value = np.zeros((lines_num, val_col_num))
vector_label = []
# splits and appends value and label using for loop statement
file_opened = open(filename)
idx = 0
for line in file_opened.readlines():
# removes all whitespace in string
line = line.strip()
# splits string according to delimiter str
list_from_line = line.split(sep=',')
# appends value to matrix and label to vector
matrix_value[idx, :] = list_from_line[val_col_st_idx : (val_col_end_idx+1)]
vector_label.append(list_from_line[label_idx])
idx += 1
return matrix_value, vector_label
위의 숫자형 데이터로 이루어진 matrix_value 를 numpy를 이용해서 표준화, 정규화하는 사용자 정의함수를 작성해보겠습니다. (물론 scipy.stats 의 zscore() 나 sklearn.preprocessing 의 StandardScaler() 함수를 사용해도 됩니다.)
아래의 사용자 정의 함수는 숫자형 데이터로 이루어진 데이터셋을 인자로 받으면, 평균(mean)과 표준편차(standard deviation)를 구하고, standardized_value = (x - mean) / standard_deviation으로 표준화를 합니다. 그리고 표준화한 matrix, 각 칼럼별 평균과 표준편차를 반환합니다.
def standardize(numeric_dataset):
# standardized_value = (x - mean)/ standard_deviation
# calculate mean and standard deviation per numeric columns
mean_val = numeric_dataset.mean(axis=0)
std_dev_val = numeric_dataset.std(axis=0)
# standardization
matrix_standardized = (numeric_dataset - mean_val)/ std_dev_val
return matrix_standardized, mean_val, std_dev_val
위의 standardize() 함수를 사용하여 matrix_value 다차원배열을 표준화해보겠습니다.
다음으로 척도, 범위가 다른 숫자형 데이터를 [0, 1] 사이의 값으로 변환하는 정규화(Normalization)를 해보겠습니다. normalized_value = (x - minimum_value) / (maximum_value - minimum_value)로 계산합니다.
CNN(Convolutional Neural Network)으로 이미지 분류 모델링할 때 보통 tensorflow나 keras 라이브러리에 이미 포함되어 있는 MNIST, CIFAR-10 같은 이미지를 간단하게 load 하는 함수를 이용해서 toy project로 연습을 해보셨을 겁니다.
그런데, 실제 이미지, 그림 파일을 분석해야 될 경우 '어? 이미지를 어떻게 업로드 하고, 어떻게 전처리하며, 어떻게 시각화해야 하는거지?'라는 의문을 한번쯤은 가져보셨을 듯 합니다.
이번 포스팅에서는 바로 이 의문에 대한 답변 소개입니다.
필요한 Python 라이브러리를 불러오겠습니다.
importnumpyas np
import pandas aspd
import matplotlib.pyplot asplt
importkeras
1. 개와 고양이 사진 다운로드 (download dogs and cats images from Kaggle)
개와 고양이 사진을 아래의 Kaggle 사이트에서 다운로드 해주세요. Kaggle 회원가입을 먼저 해야지 다운로드 할 수 있습니다. 개는 1, 고양이는 0으로 라벨링이 되어 있는 25,000 개의 이미지를 다운받을 수 있습니다.
이번 포스팅에서는 os 라이브러리를 이용한 경로 및 폴더 관리, shutil 라이브러리를 이용한 파일 복사 방법에 대한 소소한 팁들을 소개하겠습니다.
os 라이브러리에 대해서 소개해 놓은 페이지 ( https://docs.python.org/3/library/os.html )에 가보면 '기타 운영 체계에 대한 인터페이스 (Miscellaneous operating system interfaces)' 라고 소개를 하면서 스크롤 압박에 굉장히 심할 정도로 여러개의 함수들을 소개해 놓았습니다.
그 많은 것을 모두 소개하기는 힘들구요, 그중에서도 이번 포스팅에서는 제가 자주 쓰는 함수들만 몇 개 선별해서 소개하도록 하겠습니다.
1. os 라이브러리를 이용한 경로 및 폴더 생성, 조회, 변경
먼저 os 라이브러리를 불러오겠습니다.
importos # Miscellaneous operating system interfaces
1-1. 현재 작업경로 확인하기: os.getcwd()
# os.getcwd(): returns the current working directory
os.getcwd()
'C:\\Users\\admin\\python'
1-2. 작업경로 안에 들어있는 파일 리스트 확인하기: os.listdir(path)
# os.listdir(path): return a list of then entries in the directory given by path
os.listdir(os.getcwd()) # a list of files at current directory
이번 포스팅에서는 배열(array)에서 0보다 작은 수는 0으로 변환하고 나머지는 그대로 두는 여러가지 방법을 소개하겠습니다.
1. List Comprehension with for loop
2. Indexing
3. np.where(condition[, x, y])
4. np.clip(a, a_min, a_max, out=None)
1. List Comprehension: [0 if i < 0 else i for i in a]
아래처럼 for loop 을 써서 list comprehension 방법을 사용하면 특정 라이브러리의 함수를 사용하지 않아도 0보다 작은 수는 0으로 변환할 수 있습니다. 하지만, for loop 을 돌기 때문에 배열(array)가 커지면 성능이 문제될 수 있습니다. 원래의 배열 a는 그대로 있습니다.
>>> importnumpyas np
>>> a = np.arange(-5, 5)
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> [0 if i < 0 else i for i in a]
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4]
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
2. Indexing: a[a < 0] = 0
아래처럼 indexing을 사용해서 a[a < 0] = 0 처럼 0보다 작은 값이 위치한 곳에 0을 직접 할당할 수 있습니다. 이렇게 하면 원래의 배열 a가 변경됩니다.
>>> a = np.arange(-5, 5)
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> a[a < 0] = 0
>>> a
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])
3. np.where() : np.where(a < 0, 0, a)
np.where(조건, True일 때 값, False일 때 값) 를 사용하면 편리하게 0보다 작은 조건의 위치에 0을 할당할 수 있습니다. 벡터 연산을 하므로 for loop이 돌지 않아서 속도가 매우 빠릅니다. 원래의 배열 a는 변경되지 않고 그대로 있습니다.
>>> a = np.arange(-5, 5)
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> np.where(a < 0, 0, a)
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
만약 0보다 작은 수는 0으로 변환, 2보다 큰 수는 2로 변환하고 싶다면 아래처럼 np.where() 안에 np.where()를 한번 더 넣어서 써주면 되는데요, 코드가 좀 복잡해보입니다.
>>> a = np.arange(-5, 5)
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
>>>
>>> np.where(a < 0, 0, np.where(a > 2, 2, a))
array([0, 0, 0, 0, 0, 0, 1, 2, 2, 2])
4. np.clip() : np.clip(a, 0, 4, out=a)
np.clip(배열, 최소값 기준, 최대값 기준) 을 사용하면 최소값과 최대값 조건으로 값을 기준으로 해서, 이 범위 기준을 벗어나는 값에 대해서는 일괄적으로 최소값, 최대값으로 대치해줄 때 매우 편리합니다. 최소값 부분을 0으로 해주었으므로 0보다 작은 값은 모두 0으로 대치되었습니다. 이때 원래의 배열 a는 그대로 있습니다.
>>> a = np.arange(-5, 5)
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
>>> np.clip(a, 0, 4)
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])
>>> a
array([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4])
np.clip(배열, 최소값 기준, 최대값 기준, out 배열)을 사용해서 out = a 를 추가로 설정해주면 반환되는 값을 배열 a에 저장할 수 있습니다. 배열 a의 0보다 작았던 부분이 모두 0으로 대치되어 a가 변경되었음을 확인할 수 있습니다.
>>> np.clip(a, 0, 4, out=a)
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])
>>> a
array([0, 0, 0, 0, 0, 0, 1, 2, 3, 4])
최소값 기준만 적용해서 간단하게 '0'보다 작은 수는 모두 0으로 바꾸는 것은 a.clip(0) 처럼 메소드를 사용해도 됩니다.
이번 포스팅에서는 다수 그룹 별 다수의 변수 간 쌍을 이룬 상관계수 분석(paired correlation coefficients with multiple columns by multiple groups) 을 하는 방법을 소개하겠습니다.
보통 다수의 변수간의 상관계수를 구할 때는 상관계수 행렬 (correlation matrix)를 하면 되는데요, 이때 '다수의 그룹별 (by multiple groups)'로 나누어서 다수의 변수 간 상관계수를 구하려면 머리가 좀 복잡해집니다.
간단한 예제 데이터셋을 만들어서 예를 들어보겠습니다.
(1) 3개의 그룹 변수, 4개의 연속형 변수를 가진 예제 DataFrame 만들기
import numpy as np
import pandas as pd
'group_1' 변수 내 ('A', 'B' 그룹), 'group_2' 변수 내 ('C', 'D', 'E', 'F' 그룹), 'group_3' 변수 내 ('G', 'H', 'I', 'J', 'K', 'L', 'M', 'N' 그룹) 별로 나누어서 상관계수를 구해보겠습니다.
예제 데이터셋이 준비가 되었으니 이제 '그룹별로 두 개 변수 간 상관계수를 구하는 사용자 정의 함수 (a user-defined function of correlation coefficients with paired variables by groups)' 를 정의해보겠습니다.
# a user-defined function of correlation coefficients with paired variables by groups
'group_1', 'group_2', 'group_3' 의 3개의 그룹 변수로 만들어진 모든 경우의 수의 그룹 조합에 대해서, 'col_1', 'col_2', 'col_3', 'col_4'의 4개 연속형 변수로 2개씩 쌍(pair)을 이루어 만들어진 모든 경우의 수의 조합, 즉, ('col_1', 'col_2'), ('col_1', 'col_3'), ('col_1', 'col_4'), ('col_2', 'col_3'), ('col_2', 'col_4'), ('col_3', 'col_4') 의 4C2=6개의 조합별 상관계수를 구해보겠습니다.
이때 위의 (2)번에서 만들었던 '두 개 쌍의 변수간 상관계수 구하는 사용자 정의함수'인 corr_group() 함수를 사용하여 for loop 문으로 6개의 연속형 변수의 조합별로 상관계수를 구한 후에, corr_coef_df_all 데이터 프레임에 append 해나가는 방식을 사용하였습니다.
Tensorflow, Keras를 사용하는 중에 'TypeError: softmax() got an unexpected keyword argument 'axis' 의 TypeError 발생 시 업그레이드를 해주면 해결할 수 있습니다. (저는 Python 2.7 버전, Tensorflow 1.4 버전 사용 중에 Keras로 softmax() 하려니 아래의 에러 발생하였습니다)
먼저, 명령 프롬프트 창에서 Tensorflow 가 설치된 conda environment 를 활성화시켜보겠습니다.
$ conda env list
tensorflow /Users/myid/anaconda3/envs/tensorflow
$ source activate tensorflow # for mac OS
$ activate tensorflow # for Windows OS
(tensorflow) $
참고로 Python과 Tensorflow 버전 확인하는 방법은 아래와 같습니다.
(tensorflow) $ python -V
Python 2.7.14 :: Anaconda custom (64-bit)
(tensorflow) $ python
Python 2.7.14 |Anaconda custom (640bit)| (default, Oct 5 2017, 02:28:52)
[GCC 4.2.1. Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" ro "license" for more information.
Python에서 패키지 관리할 때 사용하는 pip 를 먼저 upgrade 시켜 준 후에 Tensorflow 를 업그레이트 해줍니다. Python 3.n 버전에서는 pip3 install package_name 을 사용하구요, GPU 의 경우 tensorflow-gpu 처럼 뒤에 -gpu를 추가로 붙여줍니다.