次のことを学ぶ:ソースコード,開発環境,主なプログラミング言語,どのプログラミング言語でもだいたい共通すること(オブジェクト,メソッド,データの種類)
YouTube 動画: https://www.youtube.com/watch/?v=Z2KjpYwNzOY\
次のことを学ぶ:Python プログラムの実行法,オンラインの開発環境,PythonTutor,式,変数
YouTube 動画: https://www.youtube.com/watch/?v=17ShK7KXOGY\
プログラミングの基礎である式の抽象化と関数を、Python を用いて説明
YouTube 動画: https://www.youtube.com/watch/?v=VsasG8pjhDY
Python と Google Colaboratory: 別ページ »にまとめている
第3回の内容
YouTube 動画: https://www.youtube.com/watch?v=JPeAF0TBjqg
上の動画の内容に RTools のインストールについての説明を書き加えた資料
● パッケージの設定(前準備として) install.packages("ggplot2") install.packages("dplyr") install.packages("tidyr") install.packages("magrittr") install.packages("KernSmooth") R オブジェクトのコンストラクタ x1 <- data.frame( 年次=c(1985, 1990, 1995, 2000, 2005, 2010), 出生数=c(1432, 1222, 1187, 1191, 1063, 1071), 死亡数=c(752, 820, 922, 962, 1084, 1197) ) ヒストグラム(Iris データセットのヒストグラム) library(dplyr) d2 <- tbl_df( iris ) library(tidyr) library(magrittr) library(KernSmooth) library(ggplot2) d2 %>% select( Sepal.Length, Sepal.Width, Petal.Length, Petal.Width ) %>% gather() %>% ggplot( aes(x=value, fill=key) ) + geom_histogram( binwidth=dpih( use_series(d2, Sepal.Length) ), alpha=0.5, position="identity") + theme_bw() ヒストグラムでの区間幅の調整 library(ggplot2) ggplot(iris, aes(x = Sepal.Length)) + geom_histogram(binwidth=0.1) + theme_bw() library(magrittr) library(KernSmooth) library(ggplot2) ggplot(iris, aes(x = Sepal.Length)) + geom_histogram( binwidth=dpih( iris$Sepal.Length ) ) + theme_bw() 散布図、折れ線グラフ x1 <- data.frame( 年次=c(1985, 1990, 1995, 2000, 2005, 2010), 出生数=c(1432, 1222, 1187, 1191, 1063, 1071), 死亡数=c(752, 820, 922, 962, 1084, 1197) ) library(ggplot2) ggplot(x1, aes(x=年次)) + geom_point( aes(y=出生数, colour="出生数"), size=3 ) + geom_point( aes(y=死亡数, colour="死亡数"), size=3 ) + labs(x="年次", y="出生数, 死亡数") + theme_bw() x1 <- data.frame( 年次=c(1985, 1990, 1995, 2000, 2005, 2010), 出生数=c(1432, 1222, 1187, 1191, 1063, 1071), 死亡数=c(752, 820, 922, 962, 1084, 1197) ) library(ggplot2) ggplot(x1, aes(x=年次)) + geom_point( aes(y=出生数, colour="出生数"), size=6 ) + geom_point( aes(y=死亡数, colour="死亡数"), size=6 ) + geom_line( aes(y=出生数, colour="出生数"), size=2 ) + geom_line( aes(y=死亡数, colour="死亡数"), size=2 ) + labs(x="年次", y="出生数, 死亡数") + theme_bw() x1 <- data.frame( 年次=c(1985, 1990, 1995, 2000, 2005, 2010), 出生数=c(1432, 1222, 1187, 1191, 1063, 1071), 死亡数=c(752, 820, 922, 962, 1084, 1197) ) library(ggplot2) ggplot(x1, aes(x=年次)) + geom_point( aes(y=出生数, colour="出生数"), size=6 ) + geom_point( aes(y=死亡数, colour="死亡数"), size=6 ) + stat_smooth( method="lm", se=FALSE, aes(y=出生数, colour="出生数"), size=2 ) + stat_smooth( method="lm", se=FALSE, aes(y=死亡数, colour="死亡数"), size=2 ) + labs(x="年次", y="出生数, 死亡数") + theme_bw() グラフのファイルへの保存 このプログラムで「1.png」とあるのは、グラフのファイル名です。グラフは画像ファイルとして保存されます。 x1 <- data.frame( 年次=c(1985, 1990, 1995, 2000, 2005, 2010), 出生数=c(1432, 1222, 1187, 1191, 1063, 1071), 死亡数=c(752, 820, 922, 962, 1084, 1197) ) library(ggplot2) png("1.png") ggplot(x1, aes(x=年次)) + geom_point( aes(y=出生数, colour="出生数"), size=3 ) + labs(x="年次", y="出生数") + theme_bw() dev.off() 要約統計量、頻度、ヒストグラム d1 <- data.frame( 科目=c("国語", "国語", "算数", "算数", "理科"), 受講者=c("A", "B", "A", "B", "A"), 得点=c(90, 80, 95, 90, 80) ) summary(d1) d1 <- data.frame( 科目=c("国語", "国語", "算数", "算数", "理科"), 受講者=c("A", "B", "A", "B", "A"), 得点=c(90, 80, 95, 90, 80) ) library(ggplot2) ggplot(d1, aes( x=科目, fill=科目 )) + geom_bar(stat="count") + labs(x="科目", y="総数") + theme_bw() d1 <- data.frame( 科目=c("国語", "国語", "算数", "算数", "理科"), 受講者=c("A", "B", "A", "B", "A"), 得点=c(90, 80, 95, 90, 80) ) library(ggplot2) ggplot(d1, aes( x=得点 )) + geom_bar(stat="count") + labs(x="得点", y="総数") + theme_bw()
第4回の内容
install.packages("dplyr") データフレームを CSV ファイルにエクスポート library(dplyr) d <- data_frame( name=c("apple", "rose", "rose", "tomato"), color=c("red", "white", "pink", "red"), price=c(100, 400, 200, 40) ) write.csv(d, file="C:/hoge/hoge.csv") ※ 「C:/hoge」は作業用のディレクトリ. 前もって作成しておくこと. データフレームに CSV ファイルからインポート library(dplyr) m <- read.csv(file="C:/hoge/bar.csv") print(m)
前準備 install.packages("ggplot2") install.packages("pcaPP") 主成分分析 x <- rnorm(100000, mean=5, sd=5) y <- rnorm(100000, mean=5, sd=5) n <- floor( runif(100, 1, 100000+1) ) d8 <- data.frame( xx=x[n], yy=y[n] ) d8$yy <- d8$yy - (d8$xx + d8$yy) * 0.6 library(ggplot2) ggplot(d8, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + theme_bw() a <- prcomp(d8) print(a$rotation) 主成分分析(データの合成の部分を変更) x <- rnorm(100000, mean=5, sd=5) y <- rnorm(100000, mean=5, sd=5) n <- floor( runif(100, 1, 100000+1) ) d9 <- data.frame( xx=x[n], yy=y[n] ) d9$yy <- d9$yy + (d9$xx - d9$yy) * 0.8 library(ggplot2) ggplot(d9, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + theme_bw() a <- prcomp(d9) print(a$rotation) 主成分分析は外れ値に弱い x <- rnorm(100000, mean=5, sd=5) y <- rnorm(100000, mean=5, sd=5) n <- floor( runif(100, 1, 100000+1) ) d9 <- data.frame( xx=x[n], yy=y[n] ) d9$yy <- d9$yy + (d9$xx - d9$yy) * 0.8 d10 <- data.frame( xx=rnorm(10, mean=-20, sd=1), yy=rnorm(10, mean=5, sd = 1) ) d11 <- rbind( d9, d10 ) library(ggplot2) ggplot(d11, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + theme_bw() a <- prcomp(d11) print(a$rotation) pcaPP パッケージを用いて robust PCA23:03 2021/05/17 x <- rnorm(100000, mean=5, sd=5) y <- rnorm(100000, mean=5, sd=5) n <- floor( runif(100, 1, 100000+1) ) d9 <- data.frame( xx=x[n], yy=y[n] ) d9$yy <- d9$yy + (d9$xx - d9$yy) * 0.8 d10 <- data.frame( xx=rnorm(10, mean=-20, sd=1), yy=rnorm(10, mean=5, sd = 1) ) d11 <- rbind( d9, d10 ) library(ggplot2) ggplot(d11, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + theme_bw() library(pcaPP) a2 <- PCAgrid(d11) print(a2$loadings)
X が増えると,Yが増えている.X が増えると,Y が減っている
X と Y に関係がない
二変数ともに正規分布のときに使用
求まった p 値の値が小さいときは「二変数の母平均は等しい」という仮説が棄却される
求まった p 値の値が小さくないときは,棄却ができず,結論としては何も言えないと考える.
プログラム1
x <- rnorm(100000, mean=5, sd=5) y <- rnorm(100000, mean=5, sd=5) d7 <- data.frame( xx=x[floor( runif(100, 1, 100000+1) )], yy=y[floor( runif(100, 1, 100000+1) )] ) d7$yy <- d7$yy + (d7$xx - d7$yy) * 0.6 library(ggplot2) ggplot(d7, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + theme_bw() cor(d7$xx, d7$yy)
プログラム2
x2 <- rnorm(100000, mean=5, sd=5) y2 <- rnorm(100000, mean=5, sd=0.1) d10 <- data.frame( xx=x2[floor( runif(100, 1, 100000+1) )], yy=y2[floor( runif(100, 1, 100000+1) )] ) d10$yy <- 0.1 * d10$xx + d10$yy library(ggplot2) ggplot(d10, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + xlim(-5, 15) + ylim(-5, 15) + theme_bw() cor(d10$xx, d10$yy)
プログラム3
x2 <- rnorm(100000, mean=5, sd=5) y2 <- rnorm(100000, mean=5, sd=0.1) d11 <- data.frame( xx=x2[floor( runif(100, 1, 100000+1) )], yy=y2[floor( runif(100, 1, 100000+1) )] ) d11$yy <- 0.4 * d11$xx + d11$yy library(ggplot2) ggplot(d11, aes(x=xx)) + geom_point( aes(y=yy), size=3 ) + xlim(-5, 15) + ylim(-5, 15) + theme_bw() cor(d11$xx, d11$yy)
プログラム1
t.test( c(128, 104, 124, 85, 120), c(100, 106, 89, 89, 105), var.equal=F )
プログラム2
t.test( c(128, 104, 124, 85, 120), c(180, 190, 189, 131, 130, 150), var.equal=F )
母平均は平均から、母分散は不偏分散から推定
平均や不偏分散は、標本から算出する。Rシステムでは、平均は mean、不偏分散は var である。
平均の値は母平均に近い値になり、 不偏分散の値は母分散に近い値になる可能性が高い。
機械学習の主な用途に、自動分類がある。事前に、分類済みのデータを用いて学習する。 学習ののち、自動分類できるようになる。このように、コンピュータが学習能力を持つ。
アヤメの外花被片の長さと幅、アヤメの内花被片の長さと幅、花の種類に関するデータセット
プログラム1
x <- round( rnorm(1000000, mean=100, sd=20) ) x[floor( runif(5, 1, 1000000+1) )] x[floor( runif(5, 1, 1000000+1) )] x[floor( runif(5, 1, 1000000+1) )]
プログラム2
x <- round( rnorm(1000000, mean=100, sd=20) ) m <- numeric(20) v <- numeric(20) for (i in 1:20) { s <- x[floor( runif(5, 1, 1000000+1) )] m[i] <- mean(s) v[i] <- var(s) } print(m) print(v)
プログラム3
x <- round( rnorm(1000000, mean=100, sd=20) ) m <- numeric(20) v <- numeric(20) for (i in 1:20) { s <- x[floor( runif(5, 1, 1000000+1) )] m[i] <- mean(s) v[i] <- var(s) } for (i in 1:20) { print( mean(m[1:i]) ) } for (i in 1:20) { print( mean(v[1:i]) ) }
プログラム1
install.packages("ggplot2") install.packages("dplyr") install.packages("klaR")
プログラム2
library(ggplot2) ggplot(iris, aes(x=Sepal.Length)) + geom_point( aes(y=Sepal.Width, colour=Species), size=3 ) + theme_bw()
プログラム3
library(ggplot2) ggplot(iris, aes(x=Petal.Length)) + geom_point( aes(y=Petal.Width, colour=Species), size=3 ) + theme_bw()
プログラム4
library(dplyr) library(klaR) d <- tbl_df(iris[c(3,4,5)]) partimat(Species~., data=d, method="lda")
学ぶトピックス:Web サーバ、リクエストURL、Dash
HTTP メソッド: Web サーバに対する要求内容を示すもの.GET (取得),POST(送信),PUT(送信),DELETE(削除)がある.
Web サーバ: HTTP メソッドと,リクエスト URL を受け取って処理と返答を行うサーバ
Python の Flask: Web アプリケーションのフレームワーク,Webサーバの機能を含む.リクエストURLを解析し,処理と返答を行うプログラムを簡単に書くことができる.
Flask の Web サーバ: 「app.run(debug=False, host="0.0.0.0", port=5000)」のように書くと,ポート 5000 で Flask が起動する.
Python の Dash: Dash を利用することにより,グラフの表示,Python のデータフレームの表示などが簡単にできる.
Flask でのルーティング:「@app.route('/user/<username>')」では, 「<username>」の部分は変数である. 「@app.route('/user/<username>')」は,「/user/1」や 「/user/2」や「/user/kaneko」などのさまざまなリクエスト URL にマッチする. そして,マッチした場合には,1 や 2 や kaneko が Python の変数 username に格納される.
YouTube 動画: https://www.youtube.com/watch?v=ZoZjNXpj1z
YouTube 動画: https://www.youtube.com/watch?v=8tQwAiBz2SM
Cloud FireStore [PDF], [パワーポイント]
参考資料: Python で Google Firebase の Cloud Firestore (クラウド・ファイアストア)を使ってみる
YouTube 動画: https://www.youtube.com/watch?v=GzX7ysvMQjk
参考資料: Google Firebase の Cloud FireStore を使ってみる
学習目標:Cloud FireStore: プロジェクトの作成、データベースの作成、データベース内にコレクションやドキュメントの作成。以上はWebブラウザで行う
YouTube 動画: https://www.youtube.com/watch?v=LBvcbMKxDDk
F4mapは,公開型世界地図であるOpenStreetMapを3次元表示できる機能をもった オンラインの地図サービスである. F4map の「デモ」は,Web サーバの上で動いている.緯度,経度などの情報は URL の中のパラメータとして受け取る.
F4map の URL: https://www.f4map.com/
YouTube 動画: https://www.youtube.com/watch?v=BxWbOwYPRXI
資料(Web ページ): https://www.kkaneko.jp/db/3dmap/f4map.html
OpenStreetMap は,世界規模のオンラインの地図データベースシステム.
データのダウンロードの方法は複数あるが, OpenStreetMapのページで,エクスポートする方法を案内する.これは,少量のデータをダウンロードするときに便利である. このとき,ダウンロードしたデータは XML 形式である.XML はタグ付きのドキュメントになっている.
OpenStreetMap の URL: https://www.openstreetmap.org
YouTube 動画: https://www.youtube.com/watch?v=MPxDfHo49s0
OpenStreetMap は,世界規模のオンラインの地図データベースシステム.
OpenStreetMapのユーザー登録を行うと,OpenStreetMap を編集できる権利を得ることもできる. 世界中の有志が共同制作に参画している地図データベースである. このページでは,OpenStreetMap に電子メールアドレスとパスワードを登録(ユーザー登録)の上,ログインし,OpenStreetMap のオンラインエディタ(ウェブブラウザで動く iDエディタ)を使って地図を編集する一連の手順を説明.
OpenStreetMap では,地物は,ポイント,ライン,エリアの3種類である.
OpenStreetMap の URL: https://www.openstreetmap.org
YouTube 動画: https://www.youtube.com/watch?v=5xmaAUDMbo0
資料(Web ページ): https://www.kkaneko.jp/db/map/osm.html
R システムのブログラムに対して,Web ブラウザからアクセス.
説明資料: Shiny のギャラリー [PDF], [パワーポイント]
Webブラウザでボタン,スライダ,メニュー等を操作すると,直ちに結果が得られる
Webページの中に,さまざま配置できる
Word, PDF等でのレポート生成機能もある
説明資料: Shiny の仕組み,Shiny のインストール [PDF], [パワーポイント]
Shiny の機能
R システムの標準オブジェクト
米国イエローストン公園内の間欠泉「オールド・フェイスフル・ガイザー」 その噴出持続時間 (erupition)と、噴出間隔 (waiting)
shiny のインストール
install.packages("shiny")
shiny を動かしてみる
ファイル名はこの通りにすること. 2つのファイルは、同じディレクトリ(フォルダ) に置くこと
ui.R
library(shiny) shinyUI(fluidPage( sidebarLayout( sidebarPanel( sliderInput("breaks", "please select a number:", min = 1, max = 50, value = 30) ), mainPanel( plotOutput("distPlot") ) ) ))
server.R
library(shiny) shinyServer(function(input, output) { output$distPlot <- renderPlot({ hist(faithful[,2], breaks = input$breaks) }) })
「C:/Users/user」の部分は、 実際に ui.R, server.R があるディレクトリに読み替える
library(shiny) runApp("C:/Users/user")
説明資料: Shiny のウィジェット,Shiny でテキスト表示,テーブル表示 [PDF], [パワーポイント]
library(shiny) shinyUI(fluidPage( sidebarLayout( sidebarPanel( sliderInput("breaks", "please select a number:", min = 1, max = 50, value = 30) ), mainPanel( textOutput("distPrint") ) ) )) library(shiny) shinyServer(function(input, output) { output$distPrint <- renderText({ input$breaks * 12 }) }) library(shiny) shinyUI(fluidPage( sidebarLayout( sidebarPanel ( numericInput("breaks", "value = ?", value=0) ), mainPanel( textOutput("distPrint") ) ) ))
機械学習により獲得できる能力の例:
分類、検出、認識、予測、合成、翻訳、特徴抽出など。 コンピュータがこれらを自動で行う。 学習を重ねることで、これらに上達する
機械学習
ニューラルネットワーク
ニューラルネットワークの構造
ニューラルネットワークの活性化と伝搬
学習では、正解との誤差が少なくなるように、結合の重みが自動調整される。 正解は、教師データから得られるもの。
YouTube 動画: https://www.youtube.com/watch/?v=Wx04o8U1w7c
Google Colaboratory は,オンラインで Python プログラムが編集,実行できるサイト.
TensorFlow など,人工知能の実験を行うときに便利.
YouTube 動画: https://www.youtube.com/watch/?v=Aq7kFzVszVg
ニューラルネットワークの基礎について、理解を深める。
プログラムは、次で公開
https://www.kkaneko.jp/ai/ni/index.html
Google Colaboratory のページ:
https://colab.research.google.com/drive/1IfArIvhh-FsvJIE9YTNO8T44Qhpi0rIJ?usp=sharing
.open --new C:\\sqlite3\\mydb .exit CREATE TABLE products ( id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, price REAL); INSERT INTO products VALUES( 1, 'orange', 50 ); INSERT INTO products VALUES( 2, 'apple', 100 ); INSERT INTO products VALUES( 3, 'melon', 500 ); SELECT * FROM products; SELECT * FROM products WHERE price > 90; drop table products; CREATE TABLE teacher ( id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, teacher_name TEXT NOT NULL); CREATE TABLE student ( id INTEGER PRIMARY KEY NOT NULL, student_name TEXT NOT NULL, tid INTEGER NOT NULL, score INTEGER); INSERT INTO teacher VALUES(1, 'db', 'k'); INSERT INTO teacher VALUES(2, 'python', 'a'); SELECT * FROM teacher; INSERT INTO student VALUES(1, 'kk', 1, 85); INSERT INTO student VALUES(2, 'aa', 1, 75); INSERT INTO student VALUES(3, 'nn', 1, 90); INSERT INTO student VALUES(4, 'kk', 2, 85); INSERT INTO student VALUES(5, 'nn', 2, 75); SELECT * FROM student; SELECT * FROM teacher, student WHERE teacher.id = student.tid;
https://www.kkaneko.jp/tools/win/python.html pip install -U pandas python import os os.getcwd() import pandas as pd import sqlite3 c = sqlite3.connect('hoge.sqlite') sql = u""" create table iris ( id integer primary key, sepal_length real, sepal_width real, petal_length real, petal_width real, species text ); """ c.execute(sql) x = pd.read_csv( 'c:\\iris.csv', header=0 ) for index, r in x.iterrows(): sql = u"insert into iris values (?, ?, ?, ?, ?, ?)" c.execute(sql, (r[0], r[1], r[2], r[3], r[4], r[5])) c.commit() cur = c.cursor() cur.execute(u"select * from iris") for t in cur: print (t) c.close() exit()
より詳しく学びたい人への個人ワーク
その資料: https://www.kkaneko.jp/de/db/2.html の末尾にある演習問題を試してみなさい
SQLiteman のインストール.データベースの新規作成.テーブル定義.
学ぶトピックス:オンライン地図サービス OpenStreetMap, マーカー、Folium、地図アプリ
使用するデータ: photo-2017-12-03
説明資料: 緯度経度などのデータファイルから,マーカーとイメージポップアップ付きの OpenStreetMap 地図を生成
説明資料: その2
OSMBuilding を用いて、OpenStreetMap の福山大学周辺など、いろいろな場所の3次元地図を見てみる
Microsoft Cognetive Service を動かす.(利用には Azureアカウントが必要.Azureアカウントの登録には,住所等の登録が必要.利用条件も各自で確認すること)
説明資料: 説明資料 [PDF], [パワーポイント],
さまざまな機能がある. https://docs.microsoft.com/ja-jp/azure/cognitive-services/computer-vision/ で確認できる
import tensorflow as tf import keras from keras.models import Sequential m = Sequential() from keras.layers import Dense, Activation import keras.optimizers m.add(Dense(units=64, input_dim=4)) m.add(Activation('relu')) m.add(Dense(units=3)) m.add(Activation('softmax')) m.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))
ニューラルネットワークの確認表示
print(m.summary())
ニューラルネットワークの学習を行うプログラム
import numpy as np x = np.array( [[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 1], [0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 1], [1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 0, 1], [1, 1, 1, 0], [1, 1, 1, 1]]) y = np.array( [0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0]) m.fit(x, keras.utils.to_categorical(y), epochs=500)
ニューラルネットワークを使ってみる
m.predict( np.array([[0, 1, 0, 1]]) )
第1層と第2層の間の結合の重みを表示
m.get_weights()[2]
ラズベリーパイは使わずに Windows パソコンで行う.Webブラウザを使う.
http://playground.tensorflow.org
Microsoft Cognetive Service を動かす
説明資料: 説明資料 [PDF], [パワーポイント],
さまざまな機能がある. https://docs.microsoft.com/ja-jp/azure/cognitive-services/computer-vision/ で確認できる
RStudio を起動,次のコマンドで,.dplyr パッケージをインストール
install.packages('dplyr')
説明資料: ワークスペース,セーブ, [PDF]
説明資料: データベースシステムとの連携, [PDF]