The latest Keras.io Code Examples Analysis 1 - Timeline
The Keras.io Code Example is frequently updated. To track the latest information, this code checks when the example was added or changed.
Since this post includes Python source code and HTML rendering, I recommend you to see the Google Colab environment of this ipython notebook.
Download Keras.io Code Example
This shell downloads all keras repository from github.
# download keras-io source code
!wget --no-check-certificate https://github.com/keras-team/keras-io/archive/refs/heads/master.zip
--2022-02-25 05:08:46-- https://github.com/keras-team/keras-io/archive/refs/heads/master.zip
Resolving github.com (github.com)... 140.82.112.4
Connecting to github.com (github.com)|140.82.112.4|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://codeload.github.com/keras-team/keras-io/zip/refs/heads/master [following]
--2022-02-25 05:08:46-- https://codeload.github.com/keras-team/keras-io/zip/refs/heads/master
Resolving codeload.github.com (codeload.github.com)... 140.82.121.10
Connecting to codeload.github.com (codeload.github.com)|140.82.121.10|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [application/zip]
Saving to: ‘master.zip.1’
master.zip.1 [ <=> ] 121.75M 22.7MB/s in 5.7s
2022-02-25 05:08:53 (21.2 MB/s) - ‘master.zip.1’ saved [127669641]
# unzip keras-io source code
import os
import zipfile
zf = zipfile.ZipFile('master.zip', 'r')
zf.extractall('keras-io')
examples_path = 'keras-io/keras-io-master/examples/'
# ref: https://wikidocs.net/39
def search(dir_path, list_file_path, list_dir_path, dir_path_depth):
try:
filenames = os.listdir(dir_path)
for filename in filenames:
full_filename = os.path.join(dir_path, filename)
if os.path.isdir(full_filename):
search(full_filename, list_file_path, list_dir_path, dir_path_depth)
if full_filename.count('/') == dir_path_depth:
list_dir_path.append(full_filename.split('/')[3])
else:
ext = os.path.splitext(full_filename)[-1]
if ext == '.py':
list_file_path.append(full_filename)
except PermissionError:
pass
py_files = []
catagories_path = []
search(examples_path, py_files, catagories_path, 3)
print(catagories_path)
['rl', 'keras_recipes', 'graph', 'structured_data', 'vision', 'timeseries', 'nlp', 'audio', 'generative']
Get meta information of each code example
This shell gets meta information from the first cell of each source code using parsing.
For example:
"""
Title: Image classification from scratch
Author: [fchollet](https://twitter.com/fchollet)
Date created: 2020/04/27
Last modified: 2020/04/28
Description: Training an image classifier from scratch on the Kaggle Cats vs Dogs dataset.
"""
from collections import defaultdict
import pandas as pd
def get_meta(source_code_file):
meta_dict = {}
fp = open(source_code_file, 'rt')
check = 0
while True:
line = fp.readline()
if line == '"""\n':
if check == 0:
check = 1
continue
elif check == 1:
break;
if not line:
break
tokens = line.split(':',1)
meta_dict[tokens[0]] = tokens[1].lstrip().rstrip('\n')
fp.close()
return meta_dict
meta_dict_list = {'Filename' : [],
'Category' : [],
'Title' : [],
'Author' : [],
'Date created' : [],
'Last modified' : [],
'Description' : [],
'Authors' : []}
for py_file in py_files:
meta_dict = get_meta(py_file)
meta_dict_list['Filename'].append(py_file)
meta_dict_list['Category'].append(py_file.split('/')[3])
for key in meta_dict_list.keys():
if key == 'Filename' or key == 'Category':
continue
try:
value = meta_dict[key]
meta_dict_list[key].append(value)
except KeyError:
meta_dict_list[key].append('')
Generate a dataframe from meta
This shell generates a dataframe from the meta dictionary.
# genrate dataframe from meta_dict
meta_df = pd.DataFrame(meta_dict_list)
meta_df['Date created'] = pd.to_datetime(meta_df['Date created'])
meta_df['Last modified'] = pd.to_datetime(meta_df['Last modified'])
meta_df['Link'] = meta_df['Filename'].str.replace('keras-io/keras-io-master/examples/', 'https://keras.io/examples/').str.replace('.py', '')
meta_df['Title'] = "<a href=" + meta_df['Link'] + ">" + meta_df['Title'] + "</a>"
report_df = meta_df[['Category', 'Title', 'Date created', 'Last modified']]
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:7: FutureWarning: The default value of regex will change from True to False in a future version.
import sys
Generate a plot accumulated count of code example by field
This shell generates a plot accumulated count of code example by field.
import IPython
import matplotlib.pyplot as plt
from matplotlib.dates import date2num
import matplotlib.colors as mcolors
import numpy as np
def plot_accumulated_count(title, dates, categories):
# Get some auxilliary values
min_date = date2num(dates[0])
max_date = date2num(dates[-1])
days = int(max_date - min_date + 1)
categories_key = list(set(categories))
categories_key.append('total')
# Initialize X and Y axes
x = np.arange(min_date, max_date + 1)
y = np.zeros((len(categories_key), days))
y_sum = np.zeros((len(categories_key), days))
# Iterate over dates, increase registration array
for i, date in enumerate(dates):
date_index = int(date2num(date) - min_date)
category_index = categories_key.index(categories[i])
y[category_index, date_index] += 1
y[-1, date_index] += 1 # total
for i, value in enumerate(categories_key):
y_sum[i] = np.cumsum(y[i])
color_list = list(mcolors.TABLEAU_COLORS.items())
# Plot
plt.figure(dpi=150)
for i, value in enumerate(categories_key):
plt.plot_date(x, y_sum[i], xdate=True, ydate=False, ls='-', ms=-1, linewidth=0.5, color=color_list[i][1], label = value)
plt.fill_between(x, 0, y_sum[-1], facecolor='#D0F3FF')
plt.xticks(rotation=45)
plt.legend()
plt.title(title)
plt.show()
# date plot
sorted_report_df = report_df.sort_values(by=['Date created'], ascending=True)
dates = pd.to_datetime(sorted_report_df['Date created']).tolist()
categories = sorted_report_df['Category'].tolist()
plot_accumulated_count('Keras Code Example', dates, categories)
Render a HTML from data frame sorted by date
This shell renders HTML from the data frame sorted by date.
# sorted by 'Date created'
sorted_report_df = report_df.sort_values(by=['Date created'], ascending=False)
rendering_html = sorted_report_df.to_html(render_links=True, escape=False, index=False)
IPython.display.HTML(rendering_html)
# sorted by 'Last modified'
sorted_report_df = report_df.sort_values(by=['Last modified'], ascending=False)
rendering_html = sorted_report_df.to_html(render_links=True, escape=False, index=False)
IPython.display.HTML(rendering_html)
# sorted by 'Category' and 'Date created'
sorted_report_df = report_df.sort_values(by=['Category', 'Date created'], ascending=False)
rendering_html = sorted_report_df.to_html(render_links=True, escape=False, index=False)
IPython.display.HTML(rendering_html)
# sorted by 'Category' and 'Last modified'
sorted_report_df = report_df.sort_values(by=['Category', 'Last modified'], ascending=False)
rendering_html = sorted_report_df.to_html(render_links=True, escape=False, index=False)
IPython.display.HTML(rendering_html)
책 소개
[추천사]
- 하용호님, 카카오 데이터사이언티스트 - 뜬구름같은 딥러닝 이론을 블록이라는 손에 잡히는 실체로 만져가며 알 수 있게 하고, 구현의 어려움은 케라스라는 시를 읽듯이 읽어내려 갈 수 있는 라이브러리로 풀어준다.
- 이부일님, (주)인사아트마이닝 대표 - 여행에서도 좋은 가이드가 있으면 여행지에 대한 깊은 이해로 여행이 풍성해지듯이 이 책은 딥러닝이라는 분야를 여행할 사람들에 가장 훌륭한 가이드가 되리라고 자부할 수 있다. 이 책을 통하여 딥러닝에 대해 보지 못했던 것들이 보이고, 듣지 못했던 것들이 들리고, 말하지 못했던 것들이 말해지는 경험을 하게 될 것이다.
- 이활석님, 네이버 클로바팀 - 레고 블럭에 비유하여 누구나 이해할 수 있게 쉽게 설명해 놓은 이 책은 딥러닝의 입문 도서로서 제 역할을 다 하리라 믿습니다.
- 김진중님, 야놀자 Head of STL - 복잡했던 머릿속이 맑고 깨끗해지는 효과가 있습니다.
- 이태영님, 신한은행 디지털 전략부 AI LAB - 기존의 텐서플로우를 활용했던 분들에게 바라볼 수 있는 관점의 전환점을 줄 수 있는 Mild Stone과 같은 책이다.
- 전태균님, 쎄트렉아이 - 케라스의 특징인 단순함, 확장성, 재사용성을 눈으로 쉽게 보여주기 위해 친절하게 정리된 내용이라 생각합니다.
- 유재준님, 카이스트 - 바로 적용해보고 싶지만 어디부터 시작할지 모를 때 최선의 선택입니다.