import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
iris_data=pd.read_csv("iris.csv",encoding="utf-8")
y=iris_data.loc[:,"Name"]
x=iris_data.loc[:,["SepalLength","SepalWidth","PetalLength","PetalWidth"]]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,train_size=0.8,shuffle=True)
clf=SVC()
clf.fit(x_train,y_train)
y_pred=clf.predict(x_test)
print("正解率=",accuracy_score(y_test,y_pred))import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC,LinearSVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score,classification_report
wine=pd.read_csv("wine/winequality-white.csv",sep=";",encoding="utf-8")
y=wine["quality"]
x=wine.drop("quality",axis=1)
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
model=RandomForestClassifier()
#model=LinearSVC()
#model=SVC()
#model=KNeighborsClassifier()
model.fit(x_train,y_train)
y_pred=model.predict(x_test)
print(classification_report(y_test,y_pred))
print("正解率=",accuracy_score(y_test,y_pred))import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC,LinearSVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score,classification_report
wine=pd.read_csv("wine/winequality-white.csv",sep=";",encoding="utf-8")
y=wine["quality"]
x=wine.drop("quality",axis=1)
newlist=[]
for v in list(y):
if v<=4:
newlist+=[0]
elif v<=7:
newlist+=[1]
else:
newlist+=[2]
y=newlist
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
model=RandomForestClassifier()
#model=LinearSVC()
#model=SVC()
#model=KNeighborsClassifier()
model.fit(x_train,y_train)
y_pred=model.predict(x_test)
print(classification_report(y_test,y_pred))
print("正解率=",accuracy_score(y_test,y_pred))import pandas as pd
df=pd.read_csv("kion/kion10y.csv",encoding="utf-8")
md={}
for i,row in df.iterrows():
m,d,v=(int(row['月']),int(row['日']),float(row['気温']))
key=str(m)+"/"+str(d)
if not(key in md):
md[key]=[]
md[key]+=[v]
avs={}
for key in md:
v=avs[key]=sum(md[key])/len(md[key])
print("{0} : {1}".format(key,v))なぜ温度の予測に回帰分析を使っているのかの説明。
import numpy as np
import scipy.stats as st
import sklearn.linear_model as lm
import matplotlib.pyplot as plt
%matplotlib inline
f=lamnda x:np.exp(3**x)
x_tr=np.linspace(0.,2,200)
y_tr=f(x_tr)
x=np.array([0,.1,.2,.5,.8,.9,1])
y=f(x)+np.random.randn(len(x))
plt.plot(x_tr[:100],y_tr[:100],'--k')
plt.plot(x,y,'ok',ms=10)
lr=lm.LinearRegression()
lr.fit(x[:,np.newaxis],y)
y_lr=lr.predict(x_tr[:,np.newaxis])
plt.plot(x_tr,y_tr,'--k')
plt.plot(x_tr,y_lr,'g')
plt.plot(x,y,'ok',ms=10)
plt.xlim(0,1)
plt.ylim(y.min()-1,y.max()+1)
plt.title("Linear regression")
lrp=lm.LinearRegression()
plt.plot(x_tr,y_tr,'--k')
for deg in [2,5]:
lrp.fit(np.vander(x,deg+1),y)
y_lrp=lrp.predict(np.vander(x_tr,deg+1))
plt.plot(x_tr,y_lrp,label='degree '+str(deg))
plt.legend(loc=2)
plt.xlim(0,1.4)
plt.ylim(-10,40)
print(' '.join(['%.2f' % c for c in lrp.coef_]))
plt.plot(x,y,'ok',ms=10)
plt.title("Lienar regression")アヤメの4つのパラメータを入力すると、アヤメの種類を類推して返すアプリを作成する。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>アヤメの種類教えて</title>
<script type="text/javascript" src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="js/my.js"></script>
</head>
<body>
<h1>アヤメの種類教えて</h1>
<p>4つの数値からアヤメの種類を推定して教えます。</p>
<p>がく片の長さ:<input type="text" size=10 id="SepalLength" /></p>
<p>がく片の幅 :<input type="text" size=10 id="SepalWidth" /></p>
<p>花びらの長さ:<input type="text" size=10 id="PetalLength" /></p>
<p>花びらの幅 :<input type="text" size=10 id="PetalWidth" /></p>
<p><button id="bt_teachme">教えて!</button></p>
<hr>
<p id="answer"></p>
</body>
</html>$(function () {
$("#bt_teachme").click(function () {
$.ajax({
url: "php/my.php",
type: "POST",
data: {
SepalLength: $("#SepalLength").val(),
SepalWidth: $("#SepalWidth").val(),
PetalLength: $("#PetalLength").val(),
PetalWidth: $("#PetalWidth").val()
},
dataType: "json",
timeout: 5000,
})
.done(function (data) {
$("#answer").text("sl=" + data.sl +
" sw=" + data.sw +
" pl=" + data.pl +
" pw=" + data.pw);
})
.fail(function (data) {
$("#answer").text("わかりません");
});
});
})<?php
$sl=$_POST['SepalLength'];
$sw=$_POST['SepalWidth'];
$pl=$_POST['PetalLength'];
$pw=$_POST['PetalWidth'];
$data=array(
"sl"=>$sl,
"sw"=>$sw,
"pl"=>$pl,
"pw"=>$pw
);
echo json_encode($data);
?>ここまでで、「教えて」ボタンを押すと、入力した数値が戻ってくる。
上記と同じ。
$(function () {
$("#bt_teachme").click(function () {
$.ajax({
url: "php/my.php",
type: "POST",
data: {
SepalLength: $("#SepalLength").val(),
SepalWidth: $("#SepalWidth").val(),
PetalLength: $("#PetalLength").val(),
PetalWidth: $("#PetalWidth").val()
},
dataType: "json",
timeout: 5000,
})
.done(function (data) {
$("#answer").text("そのアヤメは"+data.kind+"です。");
})
.fail(function (data) {
$("#answer").text("わかりません");
});
});
})<?php
$sl=$_POST['SepalLength'];
$sw=$_POST['SepalWidth'];
$pl=$_POST['PetalLength'];
$pw=$_POST['PetalWidth'];
$py_cmd="/home/XXXXXX/.pyenv/shims/python"; # XXXXXXはユーザ名
$ret=exec($py_cmd." judge_iris.py ".$sl." ".$sw." ".$pl." ".$pw);
$data=array(
"kind"=>$ret
);
echo json_encode($data);
?>from sklearn import datasets,svm
from sklearn.metrics import accuracy_score
from sklearn.externals import joblib
import sys
# process args
sl=sys.argv[1]
sw=sys.argv[2]
pl=sys.argv[3]
pw=sys.argv[4]
# load model
clf=joblib.load('iris.pkl')
# judge
pre=clf.predict([[sl,sw,pl,pw]])
print(pre,end="")ただし、phpフォルダ内に学習済みのモデルiris.pklを置いておく必要がある。
学習モデルは、sklearnのバージョンが違うと互換性がない場合がある。 その場合は、サーバ上で学習まで行う必要がある。
※さくらサーバーで実行する場合は、scipyのインストールができないため、現状でscikit-learnが動かない。そのため、上記のコードはそのままでは実行できない。
次世代IT人材育成セミナー?