
'빅데이터분석/파이썬 활용'에 해당되는 글 10건
- 2019.11.15
- 2019.11.15
- 2019.11.15
- 2019.11.15
- 2019.11.11
- 2019.11.11
- 2019.11.11
- 2019.11.11
- 2019.11.11
- 2019.11.11
[Solution1]
pip install pypiwin32
pip install --upgrade jupyter_client
[Solution2]
conda install -c conda-forge pywin32
conda install -c anaconda jupyter_client
conda install -c conda-forge jupyter_core
[Reference]
Python Code 함수2 (0) | 2019.11.15 |
---|---|
Python Code 함수1 (0) | 2019.11.15 |
Python Code 로직 (0) | 2019.11.15 |
!UCSD prep (0) | 2019.11.11 |
!TSNE (0) | 2019.11.11 |
[Time Function]
time.time() UTC를 이용하여 1970년1월1일 0시0분0초 기준 현재의 시간만큼 지난시간을 초단위 실수형태 반환
time.localtime(time.time()) 반환된 실수값을 이용해 년/월/일/시/분/초/... 의 튜플형태 변환
time.asctime(time.localtime(time.time())) 반환된 튜플 형태 값을 알아보기 쉬운 날짜와 시간 형태로 반환
time.ctime() time.asctime(time.localtime(time.time()))과 같은결과 반환
time.strftime('출력 포맷코드', time.localtime(time.time())) 여러가지 포맷코드로 출력
==============================
포맷코드 설명 예
%a 요일 줄임말 Mon
%A 요일 Monday
%b 달 줄임말 Jan
%B 달 January
%c 날짜와 시간을 출력함(로케일 설정에 의한 형식에 맞추어) 06/01/01 17:22:21
%d 날(day) [00,31]
%H 시간(hour)-24시간 출력 형태 [00,23]
%I 시간(hour)-12시간 출력 형태 [01,12]
%j 1년 중 누적 날짜 [001,366]
%m 달 [01,12]
%M 분 [01,59]
%p AM or PM AM
%S 초 [00,61]
%U 1년 중 누적 주-일요일을 시작으로 [00,53]
%w 숫자로 된 요일 [0(일요일),6]
%W 1년 중 누적 주-월요일을 시작으로 [00,53]
%x 현재 설정된 로케일에 기반한 날짜 출력 06/01/01
%X 현재 설정된 로케일에 기반한 시간 출력 17:22:21
%Y 년도 출력 2001
%Z 시간대 출력 대한민국 표준시
%% 문자 %
%y 세기부분을 제외한 년도 출력 01
==============================
time.sleep(a) 실수a 만큼의 시간간격을 주는 것, 주로 루프 안에서 많이 사용됨
calendar 달력을 볼 수 있게 해 주는 모듈
calendar.calendar(2001) 2001년의 전체 달력을 볼 수 있음, calendar.prcal(2001)과 같음
calendar.prmonth(2001, 4) 2001년 4월의 달력 보여줌
calendar.weekday(년도, 월, 일) 그 날짜에 해당하는 요일을 돌려줌, 0은 월요일 6은 일요일
calendar.weekday(년도, 월) 그 달의 1일이 무슨 요일인지와 몇 일까지 있는지 튜플로 반환
[Other Functions]
sys.path 모듈들이 저장되어 있는 위치로, 이 위치 파일들은 어느 경로에서도 불러올 수 있음
pickle 객체의 형태를 그대로 유지하여 파일에 저장 및 불러올 수 있게 하는 모듈
dir(string)
atof 문자열 형태의 숫자를 실수로 변환
atoi 문자열 형태의 숫자를 정수로 변환
string.zfill(a, b) a 앞의 공간을 b-len(a)만큼 0으로 채워줌
StringIO 파일처럼 취급되는 객체를 만들지만 실제 파일객체는 아니고 흉내임, 주로 저장할 필요없을 시 유용
os.environ 시스템의 환경변수 값을 딕셔너리 객체로 반환
os.chdir 현재 디렉토리 위치 변경
os.getcwd 현재 디렉토리 위치 반환
os.system("명령어") 시스템 유틸리티나 기타 명령어들 파이썬에서 호출
os.popen 시스템 명령어를 실행시킨 결과값을 읽기 모드 형태 객체로 반환
os.mkdir(디렉토리) 디렉토리를 생성한다.
os.rmdir(디렉토리) 디렉토리를 삭제한다.단, 디렉토리가 비어있어야 삭제가 가능하다.
os.unlink(파일) 파일을 지운다.
os.rename(src, dst) src라는 이름의 파일을 dst라는 이름으로 바꾼다.
shutil.copy(src, dst) src라는 이름의 파일을 dst로 복사, dst가 디렉토리 이름이면 디렉토리에 복사 하고 이름이 존재하면 덮어씀
glob(pathname) 해당 디렉토리 내의 파일들을 읽어서 리스트로 반환, *, ? 등도 사용가능
tempfile.mktemp() 중복되지 않는 임시파일의 이름을 만들어서 반환
tempfile.TemporaryFile() 임시적인 저장공간으로 사용될 파일 객체 반환, w+r이며 f.close() 호출될 때 자동으로 삭제
random.random() 0.0에서 1.0사이의 실수값 중 난수값 반환
random.randint(a, b) a와 b사이의 정수 사이에서 난수값 반환
thread 동작하고 있는 프로그램을 프로세스라 하고 한 개의 프로세스는 한가지 일만 하지만 쓰레드 이용하면 한 프로세스 내 두개 이상 동시 처리 가능
webbrowser 기본 웹브라우저가 자동으로 실행되게 하는 모듈
webbrowser.open(http://www.naver.com) 웹브라우저가 실행 상태면 해당 주소로 이동, 미실행 상태면 웹브라우저가 자동 실행되어 해당 주소로 이동
webbrowser.open_new(http://www.naver.com) 이미 웹브라우저가 실행된 상태에서 새로운 창으로 해당 주소가 열림
[Reference]
: 점프 투 파이선 (2010.12.20일 작성, 작성자: pahkey, jump2python.pdf)
Error Starting Kernel (0) | 2019.11.15 |
---|---|
Python Code 함수1 (0) | 2019.11.15 |
Python Code 로직 (0) | 2019.11.15 |
!UCSD prep (0) | 2019.11.11 |
!TSNE (0) | 2019.11.11 |
[String Function]
a.upper() 문자열 a를 모두 대문자로 바꾸어 준다.
a.count(x) 문자열 a중 x와 일치하는 것의 갯수를 반환한다.
a.find(x) 문자열 a중 문자 x가 처음으로 나온 위치를 반환한다. 없으면 -1을 반환한다.
a.index(x) 문자열 a중 문자 x가 처음으로 나온 위치를 반환한다. 없으면 에러를 발생시킨다.
a.join(s) s라는 문자열의 각각의 요소 문자사이에 문자열 a를 삽입한다.
a.lower() 문자열 a를 모두 소문자로 바꾸어 준다.
a.lstrip() 문자열 a의 왼쪽 공백을 모두 지운다.
a.rstrip() 문자열 a의 오른쪽 공백을 모두 지운다.
a.strip() 문자열 a의 양쪽 공백을 모두 지운다.
a.replace(s, r) 문자열 a의 s라는 문자열을 r이라는 문자열로 치환한다.
a.split([s]) 문자열 a를 공백으로 나누어 리스트값을 돌려준다.
a.swapcase() 문자열 a의 대문자는 소문자로, 소문자는 대문자로 각각 바꾸어 준다.
[List Function]
a.append(x) 리스트 a의 마지막에 x추가
a.sort() 리스트 a를 정렬
a.reverse() 리스트 a의 순서를 거꾸로 만든다.
a.index(x) 리스트 a에서 x를 찾아서 그 위치 반환
a.insert(i, x) 리스트 a에서 i 위치에 x 삽입
a.remove(x) 리스트 a에서 처음 나오는 x 삭제
a.pop() 리스트 a의 맨 마지막 요소 반환하고 마지막 요소 삭제
a.count(x) 리스트 a 안에 x가 몇 개 있는지를 반환
a.extend(x) 리스트 a에 리스트 x를 더함(확장)
b = a a가 가리키는 리스트를 참조 (b가 바뀌면 a도 바뀜)
b = a[:] 복사
b = copy(a) 복사
[Dictionary Function]
a.keys() 딕셔너리 a의 Key들을 모아놓은 리스트를 돌려준다.
a.values() 딕셔너리 a의 Value들을 모아놓은 리스트를 돌려준다.
a.items() 딕셔너리 a의 (Key, Value)쌍의 터플을 모아놓은 리스트를 돌려준다.
a.clear() 딕셔너리 a의 모든 Key:Value 쌍들을 삭제한다.
a.get(x) 딕셔너리 a의 Key가 x인 것의 Value를 돌려준다.
a.has_key(x) 딕셔너리 a에 x라는 Key가 있는지 조사하여 참, 거짓을 돌려준다.
[Class]
self 인스턴스의 함수로 사용하려면 무조건 사용해야함
__init__ 생성자(Constructor), 인스턴스가 만들어 질 때 호출
__del__ 소멸자(Destructor) 인스턴스가 사라질 때 호출
__add__ 연산자 "+" X + Y
__or__ 연산자 "|" X | Y
__repr__ print X
__call__ 함수호출 X()했을 때 호출
__getattr__ 자격부여 X.메소드
__getitem__ 인덱싱 X[i]
__setitem__ 인덱스 치환 X[key] = value
__getslice__ 슬라이싱 X[i:j]
__cmp__ 비교 X > Y
if __name__ == "__main__": 직접 파일 실행될 때 참이되어 문장 수행(모듈 로딩시 거짓)
[Built-in Function]
abs(x) 숫자의 절대값
abs(a+bj) = sqrt(a^2+b^2)
apply(function, (args)) 간접함수 실행 apply(sum, (3,4))
chi(i) 정수의 아스키코드갑에 해당하는 문자 출력
cmp(x, y) 두개의 객체를 비교하여 x가 크면 1, 작으면 -1, 같으면 0 반환
dir 객체가 가진 변수나 함수 리스트 출력 dir(), dir([1,2,3]), dir({'1':'a'})
divmod(a, b) 두개의 숫자에 대한 몫과 나머지를 tuple로 반환
enumerate 자료형의 순서값(첫번째)과 순서값에 해당하는 자료 실제값(두번째) 리턴
eval(expression) 입력값으로 실행가능한 문자열을 받아 결과값 반환 eval('divmod(4,3)')
execfile(file) 파이썬 파일 이름을 입력받아 실행시키는 명령 execfile('sum.py')
filter(function, list) 리스트 값 중 참인 값만 반환
hex(x) 정수값을 십육진수값으로 반환
id(object) 객체의 고유값(레퍼런스) 반환
input([prompt]) 사용자 입력을 받는 함수
int(x) 스트링 형태의 숫자나 소수점 숫자 등을 정수 형태로 반환
int(x, radix) x라는 문자열을 radix(진수) 형태로 반환
isinstance(object, class) 입력으로 받은 인스턴스가 그 클래스의 인스턴스인지 반환
lambda 함수생성 예약어로 def 쓰기 복잡하지 않거나 def 쓸수 없는 곳 사용
(lambda 인수1, 인수2, ... : 인수를 이용한 표현식)
len(s) 시퀀스 자료형의 길이를 리턴
list(s) 시퀀스 자료형을 리스트 형태로 리턴
b = list(a) a 리스트 복사한 b
long(x) 숫자 형태의 문자열이나 숫자를 long integer로 변환
map(function, list) 함수와 시퀀스 입력받아 출력을 묶어 리스트로 반환
max(s) 시퀀스 자료형들 중 최대값 리턴
min(s) 시퀀스 자료형들 중 최소값 리턴
oct(x) 정수를 8진수 문자열로 리턴
ord(c) 문자의 아스키 값 리턴
pow(x, y) x의 y승 리턴
range([start,] stop[, step]) 숫자에 해당되는 범위의 값을 리스트 형태로 반환
raw_input([prompt]) 사용자 입력을 받는 함수로 뭐든 문자로 결과 반환
reduce(function, sequence) 시퀀스 요소의 처음부터 끝까지 이어서 함수 반영 최종 리턴
reload(module) 이미 불러왔던 모듈을 다시 부르며 수정사항 바로 반영(import로 불가)
repr(object) 객체를 " " 로 둘러쌓인 문자열 형태로 리턴, 주로 eval 함수 입력으로 사용(str 불가)
sorted 입력받은 시퀀스 자료를 소트 한 후 리스트로 리턴(리스트 자료형의 sort함수는 객체를 소트할 뿐 리턴은 없음)
str(object) 객체를 문자열 형태로 반환(' '), 함수 입력으로 사용 불가한 경우 있음
tuple(object) 시퀀스 자료형을 튜플 형태로 변환
type(object) 객체의 자료형이 무엇인지 알려줌
zip 동일한 갯수의 요소값을 갖는 시퀀스 자료형을 짝으로 묶어서 리스트로 반환
[Reference]
: 점프 투 파이선 (2010.12.20일 작성, 작성자: pahkey, jump2python.pdf)
Error Starting Kernel (0) | 2019.11.15 |
---|---|
Python Code 함수2 (0) | 2019.11.15 |
Python Code 로직 (0) | 2019.11.15 |
!UCSD prep (0) | 2019.11.11 |
!TSNE (0) | 2019.11.11 |
[Escape Code]
\n 개행 (줄바꿈)
\v 수직 탭
\t 수평 탭
\r 캐리지 리턴
\f 폼 피드
\a 벨 소리
\b 백 스페이스
\000 널문자
\\ 문자 "\"
\' 단일 인용부호(')
\" 이중 인용부호(")
[String Format]
%s 문자열 (String)
%c 문자 한개(character)
%d 정수 (Integer)
%f 부동소수 (floating-point)
%o 8진수
%x 16진수
%% Literal % (문자 '%s' 자체)
%?%% ?%
%10.4f 3.1415xxxx
[True/False Setting]
""가 아닌 문자열 (예: "python") 참
"" 거짓 []가 아닌 리스트 (예: [1,2.3]) 참
[] 거짓
() 거짓
{} 거짓
0 이 아닌 숫자 (예: 1) 참
0 거짓
None 거짓
[Comparison]
x < y x가 y보다 작다
x > y x가 y보다 크다
x == y x와 y가 같다
x != y x와 y가 같지 않다
x >= y x가 y보다 크거나 같다
x <= y x가 y보다 작거나 같다
x or y x와 y 둘중에 하나만 참이면 참이다
x and y x와 y 모두 참이어야 참이다
not x x가 거짓이면 참이다
x in 리스트, x not in 리스트
x in 터플, x not in 터플
x in 문자열, x not in 문자열
[Control Statement]
pass 아무런 일도 하지 않음
break 반복문 빠져나감
continue 반복문 처음으로 돌아감
[Others]
함수의 리턴은 언제나 하나
리턴만나면 종료(아래내용 미수행됨)
입력값 초기치 설정시 초기값들 중 마지막에 반영해야함
print ?, 한줄에 결과값 계속 출력
sys.path.append 모듈디렉토리 추가
reload 모듈 파일 수정시 import는 이전 값 유지하지만 reload는 바뀐값 적용
[Reference]
: 점프 투 파이선 (2010.12.20일 작성, 작성자: pahkey, jump2python.pdf)
Python Code 함수2 (0) | 2019.11.15 |
---|---|
Python Code 함수1 (0) | 2019.11.15 |
!UCSD prep (0) | 2019.11.11 |
!TSNE (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
from keras import backend as K
from keras.utils import np_utils
from keras.layers.core import Dense, Dropout, Activation, Flatten, Reshape
from keras.layers.convolutional import Convolution3D, MaxPooling3D, AveragePooling3D
from keras.layers.convolutional import Convolution2D, MaxPooling2D, AveragePooling2D
from keras.layers import LSTM, TimeDistributed
from keras.layers import Input
from keras.models import Model
from keras.models import load_model
from keras.metrics import top_k_categorical_accuracy
from sklearn import preprocessing
from sklearn.manifold import TSNE
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import glob
import itertools
%matplotlib inline
# Hyperparameter Definition
ped2_label_by_frame = pd.read_table('./dataset/UCSDped2/label.m', header=None, skiprows=0).values
resized_as = (30, 40)
window_size = 10
label_threshold = int(window_size*0.5)
ped1_dataset_feature, ped1_dataset_label = np.zeros((0, window_size, resized_as[0], resized_as[1])), np.zeros((0, ))
normal_video_list, abnormal_video_list = sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped1/Train/*')), sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped1/Test/*'))
# Preprocessing Ped1
ped1_dataset_feature, ped1_dataset_label = np.zeros((0, window_size, resized_as[0], resized_as[1])), np.zeros((0, ))
normal_video_list, abnormal_video_list = sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped1/Train/*')), sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped1/Test/*'))
for v in abnormal_video_list:
video_index = int(v.split('/')[-1].split('Test')[-1])
video_label = ped1_label_by_frame[video_index-1]
frames = sorted(glob.glob(v+'/*.tif'))
n_frames = len(frames)
n_windows = n_frames-window_size+1
window_buffer_feature = np.zeros((n_windows, window_size, resized_as[0], resized_as[1]), dtype='int')
window_buffer_label = np.zeros((n_windows,), dtype='int')
for wi in range(n_windows):
for w in range(window_size):
n_abnormal_frame = 0
for vl in range(len(video_label[0].split(','))):
for li in range(wi+w, wi+w+window_size):
if(int(video_label[0].split(',')[vl].split(':')[0])-1<=li and li<=int(video_label[0].split(',')[vl].split(':')[1])-1):
n_abnormal_frame += 1
if(label_threshold<=n_abnormal_frame):
window_buffer_label[wi] = 1
window_buffer_feature[wi][w] = np.asarray(Image.open(frames[wi+w]).resize((resized_as[1], resized_as[0]), Image.ANTIALIAS))
ped1_dataset_feature, ped1_dataset_label = np.concatenate((ped1_dataset_feature, window_buffer_feature), axis=0), np.concatenate((ped1_dataset_label, window_buffer_label), axis=0)
print("File name: %s, n_frames: %d, n_windows: %d, Abnormal frame range: %s, n_abnormal_window: %d" %(v.split('/')[-1], n_frames, n_windows, video_label[0], len(window_buffer_label[window_buffer_label==1])))
for v in normal_video_list:
video_index = int(v.split('/')[-1].split('Train')[-1])
frames = sorted(glob.glob(v+'/*.tif'))
n_frames = len(frames)
n_windows = n_frames-window_size+1
window_buffer_feature = np.zeros((n_windows, window_size, resized_as[0], resized_as[1]), dtype='int')
window_buffer_label = np.zeros((n_windows,), dtype='int')
for wi in range(n_windows):
for w in range(window_size):
window_buffer_label[wi] = 0
window_buffer_feature[wi][w] = np.asarray(Image.open(frames[wi+w]).resize((resized_as[1], resized_as[0]), Image.ANTIALIAS))
ped1_dataset_feature, ped1_dataset_label = np.concatenate((ped1_dataset_feature, window_buffer_feature), axis=0), np.concatenate((ped1_dataset_label, window_buffer_label), axis=0)
print("File name: %s, n_frame: %d, n_windows: %d, Abnormal frame range: None, n_abnormal_window: %d" %(v.split('/')[-1], n_frames, n_windows, len(window_buffer_label[window_buffer_label==1])))
np.save('../../../dataset_tmp/ucsd/ped1_np/ped1_X_win'+str(window_size), ped1_dataset_feature), np.save('../../../dataset_tmp/ucsd/ped1_np/ped1_Y_win'+str(window_size), ped1_dataset_label)
print("Done. Dataset generated: %s, %s. Class balance: %d: %d" %(ped1_dataset_feature.shape, ped1_dataset_label.shape, ped1_dataset_label[ped1_dataset_label==0].shape[0], ped1_dataset_label[ped1_dataset_label==1].shape[0]))
# Preprocessing Ped2
ped2_dataset_feature, ped2_dataset_label = np.zeros((0, window_size, resized_as[0], resized_as[1])), np.zeros((0, ))
normal_video_list, abnormal_video_list = sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped2/Train/*')), sorted(glob.glob('../../../dataset_tmp/ucsd/UCSDped2/Test/*'))
for v in abnormal_video_list:
video_index = int(v.split('/')[-1].split('Test')[-1])
video_label = ped2_label_by_frame[video_index-1]
frames = sorted(glob.glob(v+'/*.tif'))
n_frames = len(frames)
n_windows = n_frames-window_size+1
window_buffer_feature = np.zeros((n_windows, window_size, resized_as[0], resized_as[1]), dtype='int')
window_buffer_label = np.zeros((n_windows,), dtype='int')
for wi in range(n_windows):
for w in range(window_size):
n_abnormal_frame = 0
for vl in range(len(video_label[0].split(','))):
for li in range(wi+w, wi+w+window_size):
if(int(video_label[0].split(',')[vl].split(':')[0])-1<=li and li<=int(video_label[0].split(',')[vl].split(':')[1])-1):
n_abnormal_frame += 1
if(label_threshold<=n_abnormal_frame):
window_buffer_label[wi] = 1
window_buffer_feature[wi][w] = np.asarray(Image.open(frames[wi+w]).resize((resized_as[1], resized_as[0]), Image.ANTIALIAS))
ped2_dataset_feature, ped2_dataset_label = np.concatenate((ped2_dataset_feature, window_buffer_feature), axis=0), np.concatenate((ped2_dataset_label, window_buffer_label), axis=0)
print("File name: %s, n_frames: %d, n_windows: %d, Abnormal frame range: %s, n_abnormal_window: %d" %(v.split('/')[-1], n_frames, n_windows, video_label[0], len(window_buffer_label[window_buffer_label==1])))
for v in normal_video_list:
video_index = int(v.split('/')[-1].split('Train')[-1])
frames = sorted(glob.glob(v+'/*.tif'))
n_frames = len(frames)
n_windows = n_frames-window_size+1
window_buffer_feature = np.zeros((n_windows, window_size, resized_as[0], resized_as[1]), dtype='int')
window_buffer_label = np.zeros((n_windows,), dtype='int')
for wi in range(n_windows):
for w in range(window_size):
window_buffer_label[wi] = 0
window_buffer_feature[wi][w] = np.asarray(Image.open(frames[wi+w]).resize((resized_as[1], resized_as[0]), Image.ANTIALIAS))
ped2_dataset_feature, ped2_dataset_label = np.concatenate((ped2_dataset_feature, window_buffer_feature), axis=0), np.concatenate((ped2_dataset_label, window_buffer_label), axis=0)
print("File name: %s, n_frame: %d, n_windows: %d, Abnormal frame range: None, n_abnormal_window: %d" %(v.split('/')[-1], n_frames, n_windows, len(window_buffer_label[window_buffer_label==1])))
np.save('../../../dataset_tmp/ucsd/ped2_np/ped2_X_win'+str(window_size), ped2_dataset_feature), np.save('../../../dataset_tmp/ucsd/ped2_np/ped2_Y_win'+str(window_size), ped2_dataset_label)
print("Done. Dataset generated: %s, %s. Class balance: %d: %d" %(ped2_dataset_feature.shape, ped2_dataset_label.shape, ped2_dataset_label[ped2_dataset_label==0].shape[0], ped2_dataset_label[ped2_dataset_label==1].shape[0]))
Python Code 함수1 (0) | 2019.11.15 |
---|---|
Python Code 로직 (0) | 2019.11.15 |
!TSNE (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
Python Code 편의 기능 (0) | 2019.11.11 |
from keras import backend as K
from keras.utils import np_utils
from keras.layers.core import Dense, Dropout, Activation, Flatten, Reshape
from keras.layers.convolutional import Convolution3D, MaxPooling3D, AveragePooling3D
from keras.layers.convolutional import Convolution2D, MaxPooling2D, AveragePooling2D
from keras.layers import LSTM, TimeDistributed, CuDNNLSTM
from keras.layers import Input
from keras.models import Model
from keras.models import load_model
from keras.metrics import top_k_categorical_accuracy
from sklearn import preprocessing
from sklearn.manifold import TSNE
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from PIL import Image
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import glob
import itertools
%matplotlib inline
# Load Dataset
Y_test, X_test = np.argmax(np.load('../../dataset/ucsd/ucsd_ped1/cv/Y_test_cv0_th5_sh.npy'), axis=1), np.load('../../dataset/ucsd/ucsd_ped1/cv/X_test_cv0_th5_sh.npy')
Y_train, X_train = np.argmax(np.load('../../dataset/ucsd/ucsd_ped1/cv/Y_train_cv0_th5_sh.npy'), axis=1), np.load('../../dataset/ucsd/ucsd_ped1/cv/X_train_cv0_th5_sh.npy')
# for te_idx in range(Y_test.shape[0]):
# Y_test[te_idx] = np.argmax(Y_test[te_idx])
# for tr_idx in range(Y_train.shape[0]):
# Y_train[tr_idx] = np.argmax(Y_train[tr_idx])
print Y_test.shape, X_test.shape
print Y_train.shape, X_train.shape
# Shuffle Dataset
test_idx = np.arange(Y_test.shape[0])
train_idx = np.arange(Y_train.shape[0])
np.random.shuffle(test_idx), np.random.shuffle(train_idx)
Y_test, X_test = Y_test[test_idx], X_test[test_idx]
Y_train, X_train = Y_train[train_idx], X_train[train_idx]
# Load model
model_lrcn = load_model('./model/lrcn.h5')
model_lrcn.summary()
# Plot tsne
# LRCN layer-by-layer visualization
target_model = model_lrcn
# target_layer = range(len(target_model.layers_by_depth))
# target_layer = [0, 1, 4, 6, 8, -1]
# target_layer = [-1]
tsne_model = TSNE(n_components=2, random_state=0, perplexity=50, n_iter=10000)
conf_area = np.pi*(4)**2
conf_instance = 5000
label = Y_train[:conf_instance]
feature = X_train[:conf_instance]
n_class = 2
target_layer_list = [-1, 15, 10, 4, 0]
for tl in target_layer_list:
print ('<%dth layer output>' %(tl))
intermediate_layer_model = Model(target_model.layers[0].input, target_model.layers[tl].output)
intermediate_output = intermediate_layer_model.predict(feature, batch_size=100)
tsne_input = intermediate_output
if(len(tsne_input.shape)>2):
n_instance = tsne_input.shape[0]
n_dims = len(tsne_input.shape)-1
flattened_dims = 1
for dim in range(n_dims):
flattened_dims = flattened_dims * tsne_input.shape[dim+1]
tsne_input_flattened = np.zeros((tsne_input.shape[0], flattened_dims))
for ip in range(n_instance):
tsne_input_flattened[ip] = tsne_input[ip].flatten()
tsne_output = tsne_model.fit_transform(tsne_input_flattened)
else:
tsne_output = tsne_model.fit_transform(tsne_input)
plt.figure(figsize=(30, 20))
plt.xticks([]), plt.yticks([])
print tsne_output.shape
for c in range(n_class):
label_list_bool = (label[:]==c)
n_n_class = tsne_output[label_list_bool].shape[0]
tsne_output_by_class = np.zeros((n_n_class, 2))
temp_index = 0
for r in range(conf_instance):
if(label[r]==c):
tsne_output_by_class[temp_index] = tsne_output[r]
temp_index += 1
(tsne_x, tsne_y) = (tsne_output_by_class[:, 0], tsne_output_by_class[:, 1])
if(c==0): # Normal
plt.scatter(tsne_x, tsne_y, s=conf_area, marker='+', alpha=0.5, edgecolor='black', c='b')
else: # Abnormal
plt.scatter(tsne_x, tsne_y, s=conf_area, alpha=0.5, edgecolor='black', c='r')
plt.show()
# Load model
model_lrcn = load_model('./model/lrcn_e3.h5')
model_lrcn.summary()
# Plot tsne
# LRCN layer-by-layer visualization
target_model = model_lrcn
# target_layer = range(len(target_model.layers_by_depth))
# target_layer = [0, 1, 4, 6, 8, -1]
# target_layer = [-1]
tsne_model = TSNE(n_components=2, random_state=0, perplexity=50, n_iter=10000)
conf_area = np.pi*(4)**2
conf_instance = 5000
label = Y_train[:conf_instance]
feature = X_train[:conf_instance]
n_class = 2
target_layer_list = [-1, 15]
for tl in target_layer_list:
print ('<%dth layer output>' %(tl))
intermediate_layer_model = Model(target_model.layers[0].input, target_model.layers[tl].output)
intermediate_output = intermediate_layer_model.predict(feature, batch_size=100)
tsne_input = intermediate_output
if(len(tsne_input.shape)>2):
n_instance = tsne_input.shape[0]
n_dims = len(tsne_input.shape)-1
flattened_dims = 1
for dim in range(n_dims):
flattened_dims = flattened_dims * tsne_input.shape[dim+1]
tsne_input_flattened = np.zeros((tsne_input.shape[0], flattened_dims))
for ip in range(n_instance):
tsne_input_flattened[ip] = tsne_input[ip].flatten()
tsne_output = tsne_model.fit_transform(tsne_input_flattened)
else:
tsne_output = tsne_model.fit_transform(tsne_input)
plt.figure(figsize=(30, 20))
plt.xticks([]), plt.yticks([])
print tsne_output.shape
for c in range(n_class):
label_list_bool = (label[:]==c)
n_n_class = tsne_output[label_list_bool].shape[0]
tsne_output_by_class = np.zeros((n_n_class, 2))
temp_index = 0
for r in range(conf_instance):
if(label[r]==c):
tsne_output_by_class[temp_index] = tsne_output[r]
temp_index += 1
(tsne_x, tsne_y) = (tsne_output_by_class[:, 0], tsne_output_by_class[:, 1])
if(c==0): # Normal
plt.scatter(tsne_x, tsne_y, s=conf_area, marker='+', alpha=0.5, edgecolor='black', c='b')
else: # Abnormal
plt.scatter(tsne_x, tsne_y, s=conf_area, alpha=0.5, edgecolor='black', c='r')
plt.show()
Python Code 로직 (0) | 2019.11.15 |
---|---|
!UCSD prep (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
Python Code 편의 기능 (0) | 2019.11.11 |
Jupyter Notebook을 Chrome에서 열기 (0) | 2019.11.11 |
# default
import io
import pickle
import pandas as pd
import numpy as np
import re
import glob
import itertools
# dataset
from sklearn.datasets import load_iris, make_moons, load_breast_cancer
from keras.datasets import imdb, cifar10
# preprocessing
from sklearn import preprocessing
from sklearn.preprocessing import LabelEncoder, LabelBinarizer
from sklearn.model_selection import train_test_split
from keras.utils import np_utils, multi_gpu_model
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
from sklearn.manifold import TSNE
# graphics
%matplotlib inline
import pydot
from IPython.core.display import Image
# from PIL import Image
from sklearn.tree import export_graphviz
import seaborn as sns
import mglearn
import matplotlib as mpl
import matplotlib.pyplot as plt
# general
import tensorflow as tf
from keras import layers
import keras.backend as K
from keras.layers import Input, Dense, Activation, Flatten, Dropout, BatchNormalization, Embedding, Reshape
from keras.layers.convolutional import Conv2D, Convolution2D, MaxPooling2D, AveragePooling2D, UpSampling2D
from keras.layers.convolutional import Conv3D, Convolution3D, MaxPooling3D, AveragePooling3D, UpSampling3D
from keras.layers import Conv2D, MaxPooling2D, GlobalMaxPooling2D, ZeroPadding2D, AveragePooling2D, GlobalAveragePooling2D
from keras.layers import LSTM, TimeDistributed, CuDNNLSTM
from keras.models import Model, load_model
from keras.optimizers import SGD
from keras.callbacks import EarlyStopping, ModelCheckpoint
# classification
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.neural_network import MLPClassifier
# evaluation
from sklearn.metrics import confusion_matrix, classification_report, accuracy_score
from keras.metrics import top_k_categorical_accuracy
# customize
def plot_decision_regions(X, y, model, title):
resolution = 0.01
markers = ('s', '^', 'o')
colors = ('red', 'blue', 'lightgreen')
cmap = mpl.colors.ListedColormap(colors)
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
Z = model.predict(np.array([xx1.ravel(), xx2.ravel()]).T).reshape(xx1.shape)
resolution = 0.01
markers = ('s', '^', 'o')
colors = ('red', 'blue', 'lightgreen')
cmap = mpl.colors.ListedColormap(colors)
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution), np.arange(x2_min, x2_max, resolution))
Z = model.predict(np.array([xx1.ravel(), xx2.ravel()]).T).reshape(xx1.shape)
plt.contour(xx1, xx2, Z, cmap=mpl.colors.ListedColormap(['k']))
plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8,
c=[cmap(idx)], marker=markers[idx], s=80, label=cl)
plt.xlabel(iris.feature_names[2])
plt.ylabel(iris.feature_names[3])
plt.legend(loc='upper left')
plt.title(title)
return Z
def plot_confusion_matrix(model, X_target, Y_target, label_info):
Y_pred = model.predict(X_target)
cnf_matrix = confusion_matrix(np.argmax(Y_pred, axis=1), np.argmax(Y_target, axis=1))
plt.imshow(cnf_matrix, interpolation='nearest', cmap=plt.cm.Blues)
marks = np.arange(len(label_info))
plt.xticks(marks, label_info, rotation=45)
plt.xticks(marks, label_info, rotation=45)
thresh = cnf_matrix.max()/2.
for i in range(cnf_matrix.shape[0]):
for j in range(cnf_matrix.shape[1]):
plt.text(j, i, cnf_matrix[i, j], horizontalalignment='center', color='white' if cnf_matrix[i,j]>thresh else 'black')
plt.ylabel('Actual'), plt.xlabel('Predicted')
plt.tight_layout()
plt.show()
# Preprocessing Method
def unpickle(file):
with open(file, 'rb') as fo:
data = pickle.load(fo, encoding='bytes')
return data
def load_cifar_10_data(data_dir, negatives=False):
meta_data_dict = unpickle(data_dir+'/batches.meta')
cifar_label_names = meta_data_dict[b'label_names']
cifar_label_names = np.array(cifar_label_names)
cifar_train_data = None
cifar_train_filenames = []
cifar_train_labels = []
for i in range(1, 6):
cifar_train_data_dict = unpickle(data_dir+'/data_batch_{}'.format(i))
if i==1:
cifar_train_data = cifar_train_data_dict[b'data']
else:
cifar_train_data = np.vstack((cifar_train_data, cifar_train_data_dict[b'data']))
cifar_train_filenames += cifar_train_data_dict[b'filenames']
cifar_train_labels += cifar_train_data_dict[b'labels']
cifar_train_data = cifar_train_data.reshape((len(cifar_train_data), 3, 32, 32))
if negatives:
cifar_train_data = cifar_train_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
cifar_train_data = np.rollaxis(cifar_train_data, 1, 4)
cifar_train_filenames = np.array(cifar_train_filenames)
cifar_train_labels = np.array(cifar_train_labels)
cifar_test_data_dict = unpickle(data_dir+'/test_batch')
cifar_test_data = cifar_test_data_dict[b'data']
cifar_test_filenames = cifar_test_data_dict[b'filenames']
cifar_test_labels = cifar_test_data_dict[b'labels']
cifar_test_data = cifar_test_data.reshape((len(cifar_test_data), 3, 32, 32))
if negatives:
cifar_test_data = cifar_test_data.transpose(0, 2, 3, 1).astype(np.float32)
else:
cifar_test_data = np.rollaxis(cifar_test_data, 1, 4)
cifar_test_filenames = np.array(cifar_test_filenames)
cifar_test_labels = np.array(cifar_test_labels)
return cifar_train_data, cifar_train_filenames, cifar_train_labels, cifar_test_data, cifar_test_filenames, cifar_test_labels, cifar_label_names
# Handcrafted Function Def.
def wrapped_confusion_matrix(modelInput, feature, label, class_list=["first", "second"], normalize=False, fig_size=(5,5)):
pred = modelInput.predict(feature)
cnf_matrix = confusion_matrix(np.argmax(label, axis=1), np.argmax(pred, axis=1))
np.set_printoptions(precision=2)
plt.figure(figsize=fig_size)
plt.imshow(cnf_matrix, interpolation='nearest', cmap=plt.cm.Blues)
plt.title('Confusion Matrix')
plt.xticks(np.arange(len(class_list)), class_list, rotation=45)
plt.yticks(np.arange(len(class_list)), class_list)
if(normalize):
cnf_matrix = cnf_matrix.astype('float') / cnf_matrix.sum(axis=1)[:, np.newaxis]
thresh = cnf_matrix.max() / 2.
for i, j in itertools.product(range(cnf_matrix.shape[0]), range(cnf_matrix.shape[1])):
plt.text(j, i, cnf_matrix[i, j],
horizontalalignment='center',
color='white' if cnf_matrix[i, j] > thresh else 'black')
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
def plot_history(model_input, mode='loss', val_mode=True, title='Entropy'):
history = model_input.history
if(val_mode):
plt.plot(history.history[mode])
plt.plot(history.history['val_'+mode])
plt.title(title)
plt.legend(['train', 'test'], loc='upper right')
plt.show()
else:
plt.plot(history.history[mode])
plt.title(title)
plt.legend(['train'], loc='upper right')
plt.show()
# Analysis: LRCN(2-classification)
# data loading and preprocessing
X = np.load('./dataset/ped2_X_win10.npy')
Y = np.load('./dataset/ped2_Y_win10.npy')
## transfering of data
Y = np_utils.to_categorical(Y)
print('\nRaw set of X and Y: ', X.shape, Y.shape)
## split of data
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.8, random_state=123)
print('\nTrain set: ', X_train.shape, Y_train.shape, 'Test set: ', X_test.shape, Y_test.shape)
## scaling of data
X_train, X_test = X_train/255., X_test/255.
print('\nTrain set: ', X_train.shape, Y_train.shape, 'Test set: ', X_test.shape, Y_test.shape)
## sample
plt.imshow(X[0][9])
plt.show()
## frames of specific sample
## 10 is frame of movie, 30*40 picture
sample_num = 4
random_window_idx = np.random.randint(0, X_train.shape[0], sample_num)
random_frame_idx = np.random.randint(0, 10, row_limit)
X_sample = X_train[random_window_idx]
X_sample_label = Y_train[random_window_idx]
fig, ax = plt.subplots(row_limit, 10,
subplot_kw={'xticks': [], 'yticks': []},
figsize=(15,6))
for r in range(sample_num):
for j in range(10):
ax[r][j].imshow(X_sample[r][j], cmap=plt.cm.gray)
plt.show()
# modeling
X_input = Input(X_train.shape[1:])
X_hidden = Reshape((X_train.shape[1], X_train.shape[2], X_train.shape[3], 1))(X_input)
X_hidden = TimeDistributed(Convolution2D(filters=32, kernel_size=(2, 2), padding='same', activation='relu'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2,2)))(X_hidden)
X_hidden = TimeDistributed(Convolution2D(filters=32, kernel_size=(2, 2), padding='same', activation='relu'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2,2)))(X_hidden)
X_hidden = TimeDistributed(Convolution2D(filters=32, kernel_size=(2, 2), padding='same', activation='relu'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2,2)))(X_hidden)
X_hidden = Dropout(0.5)(X_hidden)
X_hidden = Reshape((10, 3*5*32))(X_hidden)
# is same as
# X_hidden = TimeDistributed(Flatten())(X_hidden)
X_hidden = LSTM(256, return_sequences=True)(X_hidden)
X_hidden = LSTM(256, return_sequences=False)(X_hidden)
X_hidden = Dropout(0.5)(X_hidden)
X_hidden = Dense(64, activation='relu')(X_hidden)
X_output = Dense(Y_train.shape[1], activation='softmax')(X_hidden)
model_lrcn = Model(X_input, X_output)
display(model_lrcn.summary())
## optimization step
model_lrcn.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc'])
es = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto')
chk = ModelCheckpoint('./model/lrcn.h5', monitor='val_loss', verbose=1, save_best_only=False, mode='min')
model_lrcn_history = model_lrcn.fit(X_train, Y_train, validation_split=0.1, epochs=5, batch_size=64, verbose=2, shuffle=True, callbacks=[es])
# evaluation
plot_history(model_lrcm, mode='loss', title='MSE')
plot_history(model_lrcm, mode='acc', title='Accuracy')
model_lrcn.save('./model/lrcn_eval.h5')
# result
label_info = ['Normal', 'Abnormal']
plot_confusion_matrix(model_lrcn, X_test, Y_test, label_info)
wrapped_confusion_matrix(model_lrcn, X_test, Y_test, class_list=label_info, normalize=False, fig_size=(5,5))
model_lrcn.save('./model/lrcn_result.h5')
# Analysis: Convolutional Autoencoder
# modeling
## Encoder
X_input = Input(X_train.shape[1:])
X_hidden = Reshape((X_train.shape[1], X_train.shape[2], X_train.shape[3], 1))(X_input)
X_hidden = TimeDistributed(Convolution2D(filters=16, kernel_size=(2, 2), padding='same', activation='relu'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2, 2)))(X_hidden)
## Decoder
X_hidden = TimeDistributed(UpSampling2D(size=(2,2)))(X_hidden)
X_hidden = TimeDistributed(Convolution2D(filters=1, kernel_size=(2,2), padding='same', activation='relu'))(X_hidden)
X_output = Reshape((X_train.shape[1], X_train.shape[2], X_train.shape[3]))(X_hidden)
model_ae = Model(X_input, X_output)
display(model_ae.summary())
## optimization step
model_ae.compile(loss='mse', optimizer='adadelta', metrics=['kullback_leibler_divergence', 'accuracy'])
es = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto')
chk = ModelCheckpoint('./model/ae.h5', monitor='val_loss', verbose=1, save_best_only=False, mode='min')
model_ae_history = model_ae.fit(X_train, X_train, validation_split=0.1, epochs=5, batch_size=64, verbose=2, shuffle=True, callbacks=[es])
# evaluation
plot_history(model_ae, mode='loss', title='MSE')
plot_history(model_ae, mode='kullback_leibler_divergence', title='KL Divergence')
plot_history(model_ae, mode='acc', title='Accuracy')
model_ae.save('./model/ae_eval.h5')
# result
## 10 is frame of movie, 30*40 picture
sample_num = 4
random_window_idx = np.random.randint(0, X_train.shape[0], sample_num)
random_frame_idx = np.random.randint(0, 10, row_limit)
X_sample = X_train[random_window_idx]
model_ae = load_model('./model/ae_eval.h5')
X_sample_output = model_ae.predict(X_sample)
print(X_sample.shape, X_sample_output.shape)
fig, ax = plt.subplots(sample_num, 2, subplot_kw={'xticks': [], 'yticks': []}, figsize=(6, 8))
for r in range(sample_num):
ax[r][0].imshow(X_sample[r][0], cmap=plt.cm.gray)
ax[r][1].imshow(X_sample_output[r][0], cmap=plt.cm.gray)
# Analysis: Pretrained LRCN(2-classification)
# modeling
## Freeze Weight
model_ae = load_model('./model/ae_eval.h5')
for layer in model_ae.layers:
layer.trainable = False
## LRCN(2-classification)
X_hidden = model_ae.layers[3].output
X_hidden = TimeDistributed(Convolution2D(filters=32, kernel_size=(2, 2), padding='same', activation='tanh'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2, 2)))(X_hidden)
X_hidden = TimeDistributed(Convolution2D(filters=32, kernel_size=(2, 2), padding='same', activation='tanh'))(X_hidden)
X_hidden = TimeDistributed(MaxPooling2D((2, 2)))(X_hidden)
X_hidden = Dropout(0.5)(X_hidden)
X_hidden = Reshape((10, 3*5*32))(X_hidden)
X_hidden = LSTM(256, return_sequences=True)(X_hidden)
X_hidden = LSTM(256, return_sequences=False)(X_hidden)
X_hidden = Dropout(0.5)(X_hidden)
X_hidden = Dense(64, activation='tanh')(X_hidden)
X_output = Dense(Y_train.shape[1], activation='softmax')(X_hidden)
model_lrcn_fw = Model(model_ae.input, X_output)
display(model_lrcn_fw.summary())
## optimization step
model_lrcn_fw.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
es = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto')
chk = ModelCheckpoint('./model/ae.h5', monitor='val_loss', verbose=1, save_best_only=False, mode='min')
model_lrcn_fw_history = model_lrcn_fw.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=5, batch_size=64, verbose=2, shuffle=True, callbacks=[es])
# evaluation
plot_history(model_lrcn_fw, mode='loss', title='Categorical Crossentropy')
plot_history(model_lrcn_fw, mode='acc', title='Accuracy')
class_name_list_low = ['Normal', 'Abnormal']
wrapped_confusion_matrix(model_lrcn_fw, X_test, Y_test, class_list=class_name_list_low, normalize=False, fig_size=(5,5))
model_lrcn_fw.save('./model/lrcn_fw_eval.h5')
# result
label_info = ['Normal', 'Abnormal']
plot_confusion_matrix(model_lrcn_fw, X_test, Y_test, label_info)
wrapped_confusion_matrix(model_lrcn_fw, X_test, Y_test, class_list=label_info, normalize=False, fig_size=(5,5))
model_lrcn_fw.save('./model/lrcn_fw_result.h5')
!UCSD prep (0) | 2019.11.11 |
---|---|
!TSNE (0) | 2019.11.11 |
Python Code 편의 기능 (0) | 2019.11.11 |
Jupyter Notebook을 Chrome에서 열기 (0) | 2019.11.11 |
Anaconda/Theano/Tensorflow/Keras 설치 (0) | 2019.11.11 |
[Add a System Path]
import sys
new_path = '/home/kk/user_defined_modules'
if new_path not in sys.path:
sys.path.append(new_path)
[Make a new Folder]
os.getcwd()
if os.path.exists(output_path) == False:
os.makedirs(output_path)
[All Panel Shows]
%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
[Jupyter Notebook Shortcut Key]
(1) 셀 선택 모드 (Command Mode): [esc] 또는 [ctrl] + [m] 파란색 모드
위로 셀 추가: [a]
아래로 셀 추가: [b]
선택 셀 삭제: [d][d] (d를 두번 누름)
선택 셀 잘라내기: [x] (삭제로 써도 무방)
선택 셀 복사하기: [c]
선택 셀 아래에 붙여넣기: [p]
선택 셀과 아래 셀과 합치기: [shift] + [m]
실행결과 열기/닫기: [o]
Markdown으로 변경: [m]
Code로 변경: [y]
파일 저장: [ctrl] + [s] 또는 [s]
선택 셀의 코드 입력 모드로 돌아가기: [enter]
(2) 코드 입력 모드 (Edit Mode): [enter] 초록색 모드
선택 셀의 코드 전체 선택: [ctrl] + [a]
선택 셀 내 실행 취소: [ctrl] + [z]
선택 셀 내 다시 실행: [ctrl] + [y]
커서 위치 라인 주석처리: [ctrl] + [/]
선택 셀 코드 실행: [ctrl] + [enter]
선택 셀 코드 실행 후 다음 Cell로 이동: [shift] + [enter] (없으면 새로 추가)
커서 위치에서 셀 둘로 나누기: [shift] + [ctrl] + [-]
파일 저장: [ctrl] + [s]
셀 선택 모드로 돌아가기: [esc] 또는 [ctrl] + [m]
Reference: http://kkokkilkon.tistory.com/151 [꼬낄콘의 분석일지]
[Jupyter Notebook Themes]
https://www.opentutorials.org/module/2957/17787
https://github.com/dunovank/jupyter-themes/blob/master/README.md
!UCSD prep (0) | 2019.11.11 |
---|---|
!TSNE (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
Jupyter Notebook을 Chrome에서 열기 (0) | 2019.11.11 |
Anaconda/Theano/Tensorflow/Keras 설치 (0) | 2019.11.11 |
[방법1]
- 기본 브라우저를 Chrome 설정에서 바꾸고 Jupyter Notebook을 실행
[방법2]
1) 제어판 > 시스템 > 고급시스템설정 > 환경변수 > 시스템변수
2) 새로만들기
3-1) 변수이름: BROWSER
3-2) 변수값: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe (<- 크롬 위치)
!UCSD prep (0) | 2019.11.11 |
---|---|
!TSNE (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
Python Code 편의 기능 (0) | 2019.11.11 |
Anaconda/Theano/Tensorflow/Keras 설치 (0) | 2019.11.11 |
> Anaconda installation: https://anaconda.org/anaconda/python
> Theano installation: http://deeplearning.net/software/theano/install.html#install
> Tensorflow installation: https://www.tensorflow.org/install/
> Keras installation: Try "conda install keras" from Anaconda Command Prompt https://keras.io/#installation
- Keras tutorial: https://keras.io/#getting-started-30-seconds-to-keras
- Keras examples:
-- All: https://github.com/keras-team/keras/tree/master/examples
-- Simple neural network: https://github.com/keras-team/keras/blob/master/examples/mnist_mlp.py
!UCSD prep (0) | 2019.11.11 |
---|---|
!TSNE (0) | 2019.11.11 |
!UCSD_ANAMALY_DATASET + LRCN (0) | 2019.11.11 |
Python Code 편의 기능 (0) | 2019.11.11 |
Jupyter Notebook을 Chrome에서 열기 (0) | 2019.11.11 |