2019年7月14日 星期日

Python實作各種水果分類器那一種最好?

本篇文章延續上一篇:用Python實作水果分類器

水果分類器採用機器學習的技巧來實作,因此可以看出所有的演算法都是把資料分成訓練組和測試組,大家不妨找出那一種分類法,所得到分數最高,就是比較適合水果分類的方法。

求邏輯迴歸(Logistic Regression)值:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print('Accuracy of Logistic regression classifier on training set: {:.2f}'
     .format(logreg.score(X_train, y_train)))
print('Accuracy of Logistic regression classifier on test set: {:.2f}'
     .format(logreg.score(X_test, y_test)))

執行結果:

決策樹(Decision Tree):
 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)


from sklearn.tree import DecisionTreeClassifier

clf = DecisionTreeClassifier().fit(X_train, y_train)

print('Accuracy of Decision Tree classifier on training set: {:.2f}'
     .format(clf.score(X_train, y_train)))
print('Accuracy of Decision Tree classifier on test set: {:.2f}'
     .format(clf.score(X_test, y_test)))

執行結果:

設置最大決策樹深度有助於避免過度擬合(Overfitting):

 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)


from sklearn.tree import DecisionTreeClassifier
clf2 = DecisionTreeClassifier(max_depth=3).fit(X_train, y_train)
print('Accuracy of Decision Tree classifier on training set: {:.2f}'
     .format(clf2.score(X_train, y_train)))
print('Accuracy of Decision Tree classifier on test set: {:.2f}'
     .format(clf2.score(X_test, y_test)))
執行結果:

K-最近鄰居法(K-Nearest Neighbors):
 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)


from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
print('Accuracy of K-NN classifier on training set: {:.2f}'
     .format(knn.score(X_train, y_train)))
print('Accuracy of K-NN classifier on test set: {:.2f}'
     .format(knn.score(X_test, y_test)))

執行結果:


線性區別分析(

Linear Discriminant Analysis):
 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
lda = LinearDiscriminantAnalysis()
lda.fit(X_train, y_train)
print('Accuracy of LDA classifier on training set: {:.2f}'
     .format(lda.score(X_train, y_train)))
print('Accuracy of LDA classifier on test set: {:.2f}'
     .format(lda.score(X_test, y_test)))

執行結果:


單純貝氏分類器(Gaussian Naive Bayes):
 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
gnb.fit(X_train, y_train)
print('Accuracy of GNB classifier on training set: {:.2f}'
     .format(gnb.score(X_train, y_train)))
print('Accuracy of GNB classifier on test set: {:.2f}'
     .format(gnb.score(X_test, y_test)))

執行成果:


支撐向量機(support vector machine, SVM):

 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
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

from sklearn.svm import SVC
svm = SVC()
svm.fit(X_train, y_train)
print('Accuracy of SVM classifier on training set: {:.2f}'
     .format(svm.score(X_train, y_train)))
print('Accuracy of SVM classifier on test set: {:.2f}'
     .format(svm.score(X_test, y_test)))

執行結果:

2019年7月13日 星期六

用百香果資料串列來學習Python的分支

可以改變果重變數值的內容:
1
2
3
果重 = 89
大小規格='大(L)' if 果重 > 80 else '中(M)' if 果重 > 60 else '小(S)'
print(大小規格)

執行結果:

用Python實作水果分類器

程式原始碼:https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/Solving%20A%20Simple%20Classification%20Problem%20with%20Python.ipynb

水果資料來源:https://github.com/susanli2016/Machine-Learning-with-Python/blob/master/fruit_data_with_colors.txt

我們先滙入pandas和matplotlib.pyplot函式,分別用來處理資料以及繪製統計圖。首先我們先使用read_table函式來讀取fruit_data_with_colors.txt的資料,並把資料集存在fruits變數中,然後呼叫head()讀取資料前五筆資料,其程式如下:

1
2
3
4
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')
print(fruits.head())

執行結果:



若要資料集的輪廓,可以讀取shape,其程式如下:

1
2
3
4
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')
print(fruits.shape)

執行結果:共有59筆資料,有7個欄位。

若想要知道資料集中有幾種水果,可以先讀取fruit_name欄位中的資料,再使用unique()來過濾掉重覆值。

1
2
3
4
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')
print(fruits['fruit_name'].unique())

執行結果:可以看出四種水果

接下來我們來繪製數量統計圖,這時我們採用seaborn函式庫。

1
2
3
4
5
6
7
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

import seaborn as sns
sns.countplot(fruits['fruit_name'],label="Count")
plt.show()

執行結果:

為了觀察資料的變異值,我們選用盒鬚圖來繪製。

1
2
3
4
5
6
7
8
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

fruits.drop('fruit_label', axis=1).plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False, figsize=(9,9),
    title='Box Plot for each input variable')
plt.savefig('fruits_box')
plt.show()

執行結果:


接下來我們使用直方圖來表示各輸入值的分佈情形:
1
2
3
4
5
6
7
8
9
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

import pylab as pl
fruits.drop('fruit_label' ,axis=1).hist(bins=30, figsize=(9,9))
pl.suptitle("Histogram for each numeric input variable")
plt.savefig('fruits_hist')
plt.show()

執行結果:

我們來看看各變數間的相依關係:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']
cmap = cm.get_cmap('gnuplot')
scatter = pd.scatter_matrix(X, c = y, marker = 'o', s=40, hist_kwds={'bins':15}, figsize=(9,9), cmap = cmap)
plt.suptitle('Scatter-matrix for each input variable')
plt.savefig('fruits_scatter_matrix')
plt.show()

執行結果:

求邏輯迴歸分類值:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pandas as pd
import matplotlib.pyplot as plt
fruits = pd.read_table('fruit_data_with_colors.txt')

from pandas.tools.plotting import scatter_matrix
from matplotlib import cm
feature_names = ['mass', 'width', 'height', 'color_score']
X = fruits[feature_names]
y = fruits['fruit_label']

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X_train, y_train)
print('Accuracy of Logistic regression classifier on training set: {:.2f}'
     .format(logreg.score(X_train, y_train)))
print('Accuracy of Logistic regression classifier on test set: {:.2f}'
     .format(logreg.score(X_test, y_test)))

執行結果:

對於有關其他統計分析可以參考:http://www.atyun.com/14092.html

2019年7月7日 星期日

用百香果資料串列來學習Python的迴圈

參考1:How to loop with indexes in Python
參考2:從百香果分級來看Python的List串列資料結構

在Python語言中,迴圈就屬while和for兩種,我們先從while開始介紹,從參考2中,可以得知使用PassionFruit用串列方式來儲存資料。首先我們先使用一個計數器的變數i,第三行程式將i歸零,第5行程式,呼叫len()來取得串列儲存資料的個數,因此當計數器i小於List的長度時,把計數當成索引值來讀取PassionFruit串列的內容。

1
2
3
4
5
6
7
PassionFruit=['適用範圍','改良種','統一編碼','2030200000515','品名代碼','51']

i=0

while i<len(PassionFruit):
    print(PassionFruit[i])
    i+=1

執行結果:

第二種寫法,我們採用for指令,搭配range()來產生從0到len()-1的數字,這些數字會依序放在i變數中,因此就可以用i當成索引值來讀取PassionFruit的資料。

1
2
3
4
PassionFruit=['適用範圍','改良種','統一編碼','2030200000515','品名代碼','51']

for i in range(len(PassionFruit)):
    print(PassionFruit[i])

第三種寫法是最常用的,直接利用逐一檢視串列中的元素。
1
2
3
4
PassionFruit=['適用範圍','改良種','統一編碼','2030200000515','品名代碼','51']

for item in PassionFruit:
    print(item)

第四種再使用索引值。
1
2
3
4
PassionFruit=['適用範圍','改良種','統一編碼','2030200000515','品名代碼','51']

for i in range(len(PassionFruit)):
    print("PassionFruit {}: {}".format(i + 1, PassionFruit[i]))

執行結果:

最後一種採用列舉的方式,會把總共有多少的數量傳給num變數,然後再逐一的讀取串列中每個元素。
1
2
3
4
PassionFruit=['適用範圍','改良種','統一編碼','2030200000515','品名代碼','51']

for num, item in enumerate(PassionFruit):
    print("{}: {}".format(num, item))

執行結果:

2019年6月23日 星期日

百香果USR團隊用Python啟動資訊力發揮格萊珉互助精神



南開科技大學孫台平校長為大學社會責任實踐計畫-「南投百香果資源永續之煉銀網平台」計畫主持人,他以敏銳科技觀察力發現Python語言的重要性,計畫起跑,即指示煉銀網平台以Python為核心建構網路服務平台,來落實人才培育以及在地鏈結。
該計畫執行長林正敏教授以Python/Django/Mezzanine等技術發展快速地架設具有內容管理系統(Content Management System,CMS)功能的網站之動手做教材,並於107學年度第二學期於該校民生學院院必修課程「物聯網程式設計」進行試教,經由期中考評量結果不管是餐管、文創、福祉、和應外等非資訊專業系科的學生,都能順利完成CMS網站的架設。
台灣尤努斯基金會透過發展格萊珉微型信貸及社會型企業,致力於貢獻社會、改善台灣民生問題,並強化非營利組織與企業之間的合作交流。該基金會於2018年9月29日在台中市霧峰區光復新村國際NGO中心設立社會型企業創新輔育基地。尤努斯基金會董事長蔡慧玲女士邀請南開科技大學百香果USR團隊成為尤努斯社企聯盟一員。百香果USR團隊與尤努斯社企聯盟發揮格萊珉互助精神,以共享經濟模式朝輔導聯盟成員,創立社會企業來解決社會貧窮和飢餓等問題。
為了發揮格萊珉互助精神,台灣尤努斯基金會成立尤努斯社企聯盟樂學堂,舉辦一系列研習活動,包括:手拍微電影、社群行銷、啟動資訊力、以及指引技術等課程。2019年6月20日邀請「南投百香果資源永續之煉銀網平台」執行長林正敏院長分享簡易網站架設實作,活動策劃人邱仲呈先生以及李東霖先生在活動開始前非常擔憂資訊力不足的學員的學習,經由4小時的研習活動,每位學員竟然都能順利地完成Python/Django/Mezzanine的網站架設。經由大學社會責任所研發教材經由課堂試教,再擴散到社會型企業創新輔育基地的場域實作的成功,再度印證孫台平校長獨到眼光。用最好的人工智慧語言Python來發展百香果煉銀網平台是正確方向。








2019年6月22日 星期六

百香果USR團隊鏈結魚菜共生在地資源在畢業典禮舉辦期中成果展




南開科技大學在2019年6月15日舉行畢業典禮,以「南投展翅。開拓未來」為主題,期許畢業生要善用智慧科技為在地創生。南開科技大學去年以滿貫成績榮獲教育部四件兩年期大學社會責任計畫,涵蓋農業、觀光、美學、長照等主題,經由創新教學培育具備大學責任的科技人才並透過資源盤點鏈結在地資源以發展永續產業為目標。
由南開科技大學校長孫台平領軍的南投百香果資源永續之煉銀網平台團隊,選在畢業典禮舉辧期中成果展,此次主題以科技農業為主題,鏈結社團法人台灣魚菜共生產業促進會資源,展現多套魚菜共生系統。促進會理事長沈西岩先生表示:「特別感謝南開科技大學從社團法人台灣魚菜共生產業促進會籌備開始一直以共學方式支持促進會,回憶起去年成立大會選在南開科技大學舉辦,今年更結合南開百香果團隊嘗試以魚菜共生或水耕方式推出水耕百香果,未來只要經由農夫經驗以及科學數據,添加適當的養份,就能以水耕方式種出高品質的百香果」。







孫台平校長表示:「很感謝合成里社區對計畫支持,雖然本校沒有農業相關系所,但南開百香果師生團隊會更加努力以教學創新培育新農業人才,透過光電物聯網來建構智慧農業平台,這次魚菜共生或水耕百香果就是最好的應用實例」。






2019年5月28日 星期二

百香果風災後尋果與清理

5月21日早上狂風驟雨橫掃校園,午間霎時昏天暗地宛如黑夜。用過午餐,往外凝望,赫然發現整個百香果棚架倒塌,茂密翠綠的藤蔓全部鋪在地上。


果樹進入第二年,又正逢春夏之際的成長期,果實累累,盛況空前。幾千顆的果子,展示健美的姿態,誘使我們編織豐收的美夢。面膜的開發尤其仰賴這批無毒栽培的嬌客,作為乾淨的原料。
多雨濕熱的季節,病菌伺機侵擾,防治工作更加險峻。多虧陳榮煇學務長的辛勤照料,將病害降到最低。也許老天爺疼惜學務長的辛勞,選擇在此最多產的時刻,來個美麗的結束。
5月22日清除藤蔓作業展開,再見了,陪伴我們一年多的校園百香果園。
清理開始,先將可食用的果實搶救出來。





一箱又一箱




藤蔓清運
藤蔓清除工程浩大