Here’s a advanced and useful sample code using Altair, which demonstrates how to create a layered chart with interactivity, such as tooltips and selection, along with custom encoding:
import altair as alt from vega_datasets import data
# Load dataset source = data.cars()
# Define a brush selection brush = alt.selection(type='interval')
# Base chart with a scatter plot base = alt.Chart(source).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color=alt.condition(brush, 'Origin:N', alt.value('lightgray')), tooltip=['Name:N', 'Origin:N', 'Horsepower:Q', 'Miles_per_Gallon:Q'] ).properties( width=600, height=400 ).add_selection( brush )
# Layer a bar chart on top that shows the distribution of 'Origin' for selected points bars = alt.Chart(source).mark_bar().encode( x='count():Q', y='Origin:N', color='Origin:N' ).transform_filter( brush )
# Combine the scatter plot and the bar chart chart = base & bars chart
Result
Explanation
Brush Selection: An interactive selection that allows users to drag over the scatter plot to select a region.
Scatter Plot: A basic plot where points are colored by their origin, and the color changes based on the selection.
Bar Chart: Shows the distribution of car origins, updated based on the selection made in the scatter plot.
Interactivity: Tooltips provide detailed information when hovering over the points, and the chart updates dynamically based on the user’s selection.
This example combines interactivity with advanced encoding and layout, making it useful for exploratory data analysis.
# 並列化の設定 pool = multiprocessing.Pool() toolbox.register("map", pool.map)
# メイン実行ループ population = toolbox.population(n=300) NGEN = 40 for gen inrange(NGEN): offspring = toolbox.select(population, len(population)) offspring = list(map(toolbox.clone, offspring))
for child1, child2 inzip(offspring[::2], offspring[1::2]): if random.random() < 0.5: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values
for mutant in offspring: if random.random() < 0.2: toolbox.mutate(mutant) del mutant.fitness.values
invalid_ind = [ind for ind in offspring ifnot ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit inzip(invalid_ind, fitnesses): ind.fitness.values = fit
population[:] = offspring
pool.close() pool.join()
best_ind = tools.selBest(population, 1)[0] print(f"Best individual is {best_ind}, {best_ind.fitness.values}")
[実行結果]
Best individual is [-9.982904889626795, 9.853294237890143, -9.986879615364009], (296.4835618255468,)
ソースコード解説
このソースコードは、$DEAP(Distributed Evolutionary Algorithms in Python)$ライブラリを使用して、遺伝的アルゴリズムを実行するプログラムです。
遺伝的アルゴリズムは、生物の進化のプロセスに基づいた最適化手法です。
コードを説明します。
1. ライブラリのインポート
1 2 3
import random import multiprocessing from deap import base, creator, tools, algorithms
defcustom_mutation(individual, indpb): for i inrange(len(individual)): if random.random() < indpb: individual[i] = random.uniform(-10, 10) return individual,
population = toolbox.population(n=300) NGEN = 40 for gen inrange(NGEN): offspring = toolbox.select(population, len(population)) offspring = list(map(toolbox.clone, offspring))
for child1, child2 inzip(offspring[::2], offspring[1::2]): if random.random() < 0.5: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values
for mutant in offspring: if random.random() < 0.2: toolbox.mutate(mutant) del mutant.fitness.values
invalid_ind = [ind for ind in offspring ifnot ind.fitness.valid] fitnesses = toolbox.map(toolbox.evaluate, invalid_ind) for ind, fit inzip(invalid_ind, fitnesses): ind.fitness.values = fit
population[:] = offspring
pool.close() pool.join()
初期個体群($300$個体)を生成し、$40$世代にわたって進化させます。
各世代で選択、交叉、突然変異を行い、新しい個体群を生成します。
不正な適応度を持つ個体を評価し、適応度を更新します。
10. 最良の個体の表示
1 2
best_ind = tools.selBest(population, 1)[0] print(f"Best individual is {best_ind}, {best_ind.fitness.values}")
最良の個体を選択し、その個体と適応度を表示します。
このコードは、遺伝的アルゴリズムを使用して3次元ベクトルの最適化を行うプログラムです。
各世代で選択、交叉、突然変異を行い、最適な個体を見つけるために進化を繰り返します。
最終的に、最も適応度の高い個体が表示されます。
結果解説
表示された結果について、説明します。
出力結果
1
Best individual is [-9.982904889626795, 9.853294237890143, -9.986879615364009], (296.4835618255468,)