• Skip to main content
  • Skip to primary sidebar

学習記録

グラフ

周期表をbokehでhtml出力

2018年4月18日 by 河副 太智 Leave a Comment

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
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, HoverTool
from bokeh.plotting import figure
from bokeh.sampledata.periodic_table import elements
from bokeh.transform import dodge, factor_cmap
 
output_file("period.html")
 
periods = ["I", "II", "III", "IV", "V", "VI", "VII"]
groups = [str(x) for x in range(1, 19)]
 
df = elements.copy()
df["atomic mass"] = df["atomic mass"].astype(str)
df["group"] = df["group"].astype(str)
df["period"] = [periods[x-1] for x in df.period]
df = df[df.group != "-"]
df = df[df.symbol != "Lr"]
df = df[df.symbol != "Lu"]
 
cmap = {
    "alkali metal"         : "#a6cee3",
    "alkaline earth metal" : "#1f78b4",
    "metal"                : "#d93b43",
    "halogen"              : "#999d9a",
    "metalloid"            : "#e08d49",
    "noble gas"            : "#eaeaea",
    "nonmetal"             : "#f1d4Af",
    "transition metal"     : "#599d7A",
}
 
source = ColumnDataSource(df)
 
p = figure(title="Periodic Table (omitting LA and AC Series)", plot_width=1000, plot_height=450,
           tools="", toolbar_location=None,
           x_range=groups, y_range=list(reversed(periods)))
 
p.rect("group", "period", 0.95, 0.95, source=source, fill_alpha=0.6, legend="metal",
       color=factor_cmap('metal', palette=list(cmap.values()), factors=list(cmap.keys())))
 
text_props = {"source": source, "text_align": "left", "text_baseline": "middle"}
 
x = dodge("group", -0.4, range=p.x_range)
 
r = p.text(x=x, y="period", text="symbol", **text_props)
r.glyph.text_font_style="bold"
 
r = p.text(x=x, y=dodge("period", 0.3, range=p.y_range), text="atomic number", **text_props)
r.glyph.text_font_size="8pt"
 
r = p.text(x=x, y=dodge("period", -0.35, range=p.y_range), text="name", **text_props)
r.glyph.text_font_size="5pt"
 
r = p.text(x=x, y=dodge("period", -0.2, range=p.y_range), text="atomic mass", **text_props)
r.glyph.text_font_size="5pt"
 
p.text(x=["3", "3"], y=["VI", "VII"], text=["LA", "AC"], text_align="center", text_baseline="middle")
 
p.add_tools(HoverTool(tooltips = [
    ("Name", "@name"),
    ("Atomic number", "@{atomic number}"),
    ("Atomic mass", "@{atomic mass}"),
    ("Type", "@metal"),
    ("CPK color", "$color[hex, swatch]:CPK"),
    ("Electronic configuration", "@{electronic configuration}"),
]))
 
p.outline_line_color = None
p.grid.grid_line_color = None
p.axis.axis_line_color = None
p.axis.major_tick_line_color = None
p.axis.major_label_standoff = 0
p.legend.orientation = "horizontal"
p.legend.location ="top_center"
 
show(p)

 

Filed Under: Bokeh, グラフ Tagged With: Bokeh

Bokehで動かせるグラフを作成

2018年4月10日 by 河副 太智 Leave a Comment

Bokehはインタラクティブなグラフを作成できるデータ可視化ライブラリです。

 

インストール

インストール方法Anadonda使用

1
conda install bokeh

pipの場合

1
pip install bokeh

詳細は、公式ドキュメントを御覧下さい。

 

更に容量の大きなサンプルデータをダウンロード

1
$bokeh sampledata

あるいは、Pythonのインタープリタ上でもダウンロード可能

1
2
import bokeh.sampledata
bokeh.sampledata.download()

 

テスト

Jupyter notebookで実行 ※現時点ではJupyter labでは使用不可

1
2
3
4
from bokeh.io import output_notebook
from bokeh.io import show
output_notebook()

BokehJS 0.12.15 successfully loaded.と出ればOK

 

 

スライダー

次にスライダーの設定をしますIpywidgetsをインポート

pip

1
2
pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension

conda

1
conda install -c conda-forge ipywidgets

 

コード

1
2
3
from ipywidgets import IntSlider
slider = IntSlider(value=50)#valueの値は可変
slider

 

bokehスライダー

 

これでJupyter上でスライダーが動きます

この状態では中心が50となりスライダーを右端に移動させると
100になります。

画面上でvalueを変更する以外にも以下のように記述すれば
スライダーの位置の変更が可能です。

1
slider.value = 100

 

手動でsliderを移動させた場合

1
slider.value

逆にスライダーの位置の値を取得する事も可能

 

 

HTMLでリアルタイム表示

1
2
3
4
from ipywidgets import HTML
 
text = HTML("スライダーの値は{}".format(slider.value))
text

スライダーの値は50と表示されます


http://harmonizedai.com/article/wp-content/uploads/2018/04/bokenhtml.mp4

 

 

 

bqplot(二次元プロット)

bqplotドキュメント

 

pip

1
2
pip install bqplot
jupyter nbextension enable --py --sys-prefix bqplot

conda

1
conda install -c conda-forge bqplot

 

Filed Under: グラフ

複数のグラフを表示

2018年1月25日 by 河副 太智 Leave a Comment

複数のグラフを表示

ax=ax1
と
ax=ax2で分ける

1
2
3
4
5
6
df = pd.read_csv('train.csv')
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax2 = fig.add_subplot(1,2,2)
sns.barplot(x="Age",y="Sex",hue='Survived',data=df, ax=ax1)
sns.countplot('Sex',hue='Survived',data=df, ax=ax2)

 

Filed Under: グラフ

matplotlibでグラフをpngに変換

2018年1月24日 by 河副 太智 Leave a Comment

matplotlibでグラフをpngに変換

1
2
3
4
5
6
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
 
plt.plot([1,2,3,4,5,4,3,2,1])
plt.savefig("aaa.png")

 

Filed Under: グラフ

データ平均値から要素と目的データの関連を可視化

2018年1月15日 by 河副 太智 Leave a Comment

seabornでデータ平均値から要素と目的データの関連を可視化

 

タイタニックの乗客の年齢をx、性別をyとして生存の有無を表示
男性と女性に分けて、更に生存の有無を分け、更に平均年齢をグラフ表示

1
2
3
4
5
6
7
8
9
10
11
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
 
 
#csvファイルをデータフレームに読み込む
df = pd.read_csv('train.csv')
 
#seabornでデータプロットすると
sns.barplot(x="Age",y="Sex",hue='Survived',data=df)

 

 

Filed Under: グラフ

ユーザー、自分の問いに答える(アイリス)

2018年1月1日 by 河副 太智 Leave a Comment

ユーザーがアイリスの形状を4種類指定して、
それがどの種類のアイリスになるのかを予測する

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
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn
import mglearn
 
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from IPython.display import display
from sklearn.neighbors import KNeighborsClassifier
 
%matplotlib inline
 
 
 
iris_dataset = load_iris()
 
#花の特徴左からガクの長さ、ガクの幅、花弁の長さ、花弁の幅
#トータル150のデータの内10個を表示
print("◆最初の10個のカラムデータ:\n\n{}".format(iris_dataset["data"][:10]))
 
#上記のdataに対する答え [0=setosa,1=versicolor,2=virginica]
print("\n◆上記データに対する答え [0=setosa,1=versicolor,2=virginica]:\n{}".format(iris_dataset["target"][:10]))
 
#学習用に75%テスト用に25%に分ける
X_train,X_test,y_train, y_test = train_test_split(
    iris_dataset["data"],iris_dataset["target"],random_state=0)
 
#X_trainは(112, 4)となる、これは上記で75%に分けた112の花びらのデータ数と
#そのデータの要素4つ分になる
print("\n◆75%に分けた112の花びらのデータ数とそのデータの要素4つ:\n{}".format(X_train.shape))
 
#y_trainは(112)となる、これは上記で75%に分けた花びらの種類の答え(0,1,2)の
#どれか一つが入っている
print("\n◆75%に分けた花びらの種類の答え(0,1,2)のどれか一つ:\n{}".format(y_train.shape))
 
#X_testは(38,4)となるこれは上記で25%に分けた38の花びらのデータ数と
#そのデータの要素4つ分になる
print("\n◆25%に分けた38の花びらのデータ数とそのデータの要素4つ分:\n{}".format(X_test.shape))
 
#y_test shapeは(38.)となるこれは上記で25%に分けた花びらの種類の答え(0,1,2)の
#どれか一つが入っている
print("\n◆25%に分けた38の花びらの種類の答え(0,1,2)のどれか一つ:\n{}".format(y_test.shape))
 
#[データの検査]
#答えである(0,1,2)がある程度分離できているかどうかを可視化する
#アイリスの種類ごとに色を変えて表示する、この場合は3点がある程度分離できていれば
#訓練できる可能性が高いと言える、逆にゴチャゴチャであれば学習は難しい
 
#1.X_trainのデータからDataFrameを作る
#iris_dataset.feature_namesの文字列をつかってカラムに名前を付ける
iris_dataframe = pd.DataFrame(X_train,columns=iris_dataset.feature_names)
 
#データフレームからscatter matrixを作成し、y_trainに従って色をつける
pd.plotting.scatter_matrix(iris_dataframe,c=y_train,figsize=(15,15),marker="o",
                        hist_kwds={"bins":20},s=60,alpha=.8,cmap=mglearn.cm3)
 
#KNeighborsClassifierをfitで(X_train,y_train)を予測
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
 
 
#KNeighborsClassifierにて行った予測の精度を確認
print("◆KNeighborsClassifierにて行った予測の精度を確認:\n{:.2f}".format(knn.score(X_test, y_test)))
 
 
#ユーザーからの問いに対する予測を行う[5,2.9,1,0.2]がユーザーからの問い
X_new = np.array([[5,2.9,1,0.2]])
 
#元のX_test.shapeと同じ配列でなければいけないので配列形式を確認
print("◆元のデータの配列形式:\n{}".format(iris_dataset["data"][:1]))
print("◆ユーザーデータの配列形式(元と同じ形なのでOK):\n{}".format(X_new))
 
 
 
prediction = knn.predict(X_new)
print("◆0,1,2のどれを選択したか:\n{}".format(prediction))
print("◆ターゲット(花の名前):\n{}".format(iris_dataset["target_names"][prediction]))

 

結果

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
◆最初の10個のカラムデータ:
 
[[ 5.1  3.5  1.4  0.2]
[ 4.9  3.   1.4  0.2]
[ 4.7  3.2  1.3  0.2]
[ 4.6  3.1  1.5  0.2]
[ 5.   3.6  1.4  0.2]
[ 5.4  3.9  1.7  0.4]
[ 4.6  3.4  1.4  0.3]
[ 5.   3.4  1.5  0.2]
[ 4.4  2.9  1.4  0.2]
[ 4.9  3.1  1.5  0.1]]
 
◆上記データに対する答え [0=setosa,1=versicolor,2=virginica]:
[0 0 0 0 0 0 0 0 0 0]
 
◆75%に分けた112の花びらのデータ数とそのデータの要素4つ:
(112, 4)
 
◆75%に分けた花びらの種類の答え(0,1,2)のどれか一つ:
(112,)
 
◆25%に分けた38の花びらのデータ数とそのデータの要素4つ分:
(38, 4)
 
◆25%に分けた38の花びらの種類の答え(0,1,2)のどれか一つ:
(38,)
◆KNeighborsClassifierにて行った予測の精度を確認:
0.97
◆元のデータの配列形式:
[[ 5.1  3.5  1.4  0.2]]
◆ユーザーデータの配列形式(元と同じ形なのでOK):
[[ 5.   2.9  1.   0.2]]
◆0,1,2のどれを選択したか:
[0]
◆ターゲット(花の名前):
['setosa']

 

 

Filed Under: scikit-learn, グラフ, 作成実績, 教師有り, 機械学習

  • « Go to Previous Page
  • Page 1
  • Page 2
  • Page 3
  • Page 4
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in