皮卡丘
妙蛙種子
打開 Jupyter 新增一個 python 檔~
# 這是註解!
# 用一個井字號
# 在這裡講話電腦不會知道
# 通常用來提醒自己程式在幹麻~
# [函式格式] 機器名稱(放入機器的東西)
# print 是一台印表機
print("hello world!")
name = "PIKA" # 字串(話)要加" "
age = 20 # 數字 不用加" "
# 印出來試試看
print(name)
print(age)
print(age+1)
我想記錄每個同學的名字!
student1 = "pikachu"
student2 = "hebe"
student3 = "IU"
student4 = "I am so tired...."
students = ["pikachu", "hebe", "IU", "Mr. happy"]
# 櫃子從零號開始算
print(students[0])
print(students[3])
students.append("Mrs. new")
print(students)
# [定義函式格式] def 函式名稱(函式參數):
def my_add(a, b):
# 用 tab 代表函式裡面的程式
# [回傳格式] return 回傳的東西
return a+b
# 這裡是機器外面了,呼叫函式!
my_add(32, 3)
有禮貌地說十次你好!
print("你好")
print("你好")
print("你好")
print("你好")
… 手寫好累
重複執行!
# 重複做 10 次
for i in range(10):
#tab 代表下面的內容在迴圈裡面
print("你好")
叫出每一個同學的名字!
# 每次找一個 students 裡面的每個名字 name
# 印出 name
for name in students:
print(name)
拾人牙慧 :)
# import 套件名字
import keras
import os
# import 套件名字 as 幫他取個綽號
import numpy as np
import matplotlib.pyplot as plt
# from 套件名稱 import 套件裡的特定函式
from PIL import Image
from random import shuffle
Run!
定義一個函式,準備讀圖片!
def load_data(dir_path):
data = [] #紀錄資料,一開始沒有圖片
return data #回傳資料陣列
train_data = load_data("./data/train")
print(train_data)
找到 data 資料夾底下的所有資料夾
def load_data(dir_path):
data = []
# 對 data 資料夾裡的所有資料夾做事
for pokemon_name in os.listdir(dir_path):
print(pokemon_name)
# 把 pokemon_name 加到照片路徑的後面,變成新路徑
pokemon_path = os.path.join(dir_path, pokemon_name)
print(pokemon_path)
return data
# 呼叫函式
train_data = load_data("./data/train")
找到寶可夢資料夾底下的所有檔案
def load_data(dir_path):
data = []
for pokemon_name in os.listdir(dir_path):
pokemon_path = os.path.join(dir_path, pokemon_name)
# 對每一個寶可夢資料夾裡面的東西做事
for img_file in os.listdir(pokemon_path):
path = os.path.join(pokemon_path, img_file)
print(path)
return data
train_data = load_data("./data/train")
def load_data(dir_path):
data = []
for pokemon_name in os.listdir(dir_path):
# ... 省略
for img_file in os.listdir(pokemon_path):
path = os.path.join(pokemon_path, img_file)
# 把圖片存起來
img = Image.open(path)
data.append(np.array(img))
return data
印出圖片看看
# 把照片 show 出來!
train_data = load_data("./data/train")
plt.imshow(train_data[0]) #第一張照片
把圖片縮小!
IMG_SIZE = 96
def load_data(dir_path):
data = []
for pokemon_name in os.listdir(dir_path):
# ... 省略
for img_file in os.listdir(pokemon_path):
path = os.path.join(pokemon_path, img_file)
img = Image.open(path)
# 把圖片縮小
img = img.resize((IMG_SIZE, IMG_SIZE),
Image.ANTIALIAS)
# 除以 255!
data.append(np.array(img)/255.)
#shuffle!
shuffle(data)
return data
再印出圖片
皮卡丘 妙蛙種子
可能預測結果
[ 0.7 , 0.3 ]
皮卡丘 妙蛙種子 小火龍
定義一個新的函式分標籤!
# 宣告有哪些寶可夢
POKEMONS = ["pikachu", "bulbasaur", "charmander", "squirtle"];
def label_img(pokemon_name):
arr = np.zeros(len(POKEMONS))
ind = POKEMONS.index(pokemon_name)
arr[ind] = 1
return arr
label_img("pikachu")
def load_data(dir_path):
data = []
IMG_SIZE = 96
def load_data(dir_path):
data = []
for pokemon_name in os.listdir(dir_path):
# 查找標籤
label = label_img(pokemon_name)
# ... 省略
for img_file in os.listdir(pokemon_path):
# ... 省略
# 把標籤也加入 data
data.append([np.array(img)/255., label])
shuffle(data)
return data
印出圖片+標籤
# 把照片 show 出來!
train_data = load_data("./data/train")
plt.imshow(train_data[0][0])
print(train_data[0][1])
試試看 test 資料夾裡的
test_data = load_data("./data/test")
把圖書館分成:圖片圖書館、標籤圖書館
train_image = np.array([i[0] for i in train_data])
train_label = np.array([i[1] for i in train_data])
test_image = np.array([i[0] for i in test_data])
test_label = np.array([i[1] for i in test_data])
0x0 + 0x0 + 0x1+ 0x1 + 1x0 + 0x0 + 0x0 + 0x1 + 0x1 = 0
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Flatten,Dense
from keras.layers import BatchNormalization
from keras.layers import Dropout, Activation
model = Sequential()
#model.add()
# 每張圖的大小
INPUT_SHAPE = (IMG_SIZE, IMG_SIZE, 3)
model = Sequential()
# 新增一層 convolution layer
model.add(Conv2D(32, kernel_size = (3, 3),
activation = 'relu', input_shape = INPUT_SHAPE))
# 新增一層 maxpooling
model.add(MaxPooling2D(pool_size = (2,2)))
# 新增一層做 normalize
model.add(BatchNormalization())
# 把圖片拉平,轉成一維陣列
model.add(Flatten())
# 新增一層 128 個 node 的 hidden layer
model.add(Dense(128, activation='relu'))
# 新增一層 4 個 node 的 output layer
model.add(Dense(len(POKEMONS), activation = 'softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics = ['accuracy'])
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics = ['accuracy'])
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics = ['accuracy'])
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics = ['accuracy'])
history = model.fit(train_image, train_label,
batch_size = 50, validation_split = 0.2,
epochs = 20, verbose = 1)
印印看!
print(history.history['acc'])
print(history.history['val_acc'])
def show_train_history(train_acc, validation_acc):
plt.plot(history.history[train_acc])
plt.plot(history.history[validation_acc])
plt.title('Train History')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['train', 'validation'], loc='upper left')
plt.show()
show_train_history('acc', 'val_acc')
loss, acc = model.evaluate(test_image, test_label, verbose = 1)
print(acc * 100)
# 測試第0張照片!
result = model.predict(np.array(test_image[0]).reshape(-1,
IMG_SIZE, IMG_SIZE, 3))
plt.imshow(test_image[0])
print(result)
result = model.predict(np.array(test_image[0]).reshape(-1, IMG_SIZE, IMG_SIZE, 3))
# 找到陣列裡最大的位置
predict_ind = np.argmax(result[0])
# 印出預測寶可夢、預測的準確度
print(POKEMONS[predict_ind], result[0][predict_ind] * 100)
# 印出照片
plt.imshow(test_image[0])
傳新照片!
#讀照片~
img = Image.open("my_pika.jpg")
img = img.resize((IMG_SIZE, IMG_SIZE), Image.ANTIALIAS)
result = model.predict(np.array(img).reshape(-1, IMG_SIZE, IMG_SIZE, 3))
# 找到陣列裡最大的位置
predict_ind = np.argmax(result[0])
# 印出預測寶可夢、預測的準確度
print(POKEMONS[predict_ind], result[0][predict_ind] * 100)
# 印出照片
plt.imshow(img)
# 試試看多加幾層layer!
model.add(Conv2D(64, kernel_size=(3,3),
activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization())
# 把一些 node 去掉
model.add(Dropout(0.2))
from keras.models import load_model
model.save('pokemon_model.h5')
from keras.models import load_model
model = load_model('pokemon_model.h5')