Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Keras ดึงและนำโหนดในกราฟเลเยอร์ไปใช้ซ้ำด้วย Python

Keras พัฒนาขึ้นภายใต้โครงการ ONEIROS (Open-ended Neuro-Electronic Intelligent Robot Operating System) เป็น Deep Learning API ระดับสูง เขียนด้วย Python ให้อินเทอร์เฟซที่ใช้งานได้ผลลัพธ์รวดเร็ว รันบน TensorFlow รองรับการขยายสเกล (Scalable) และ Cross-platform (รันบน TPU, GPU clusters, เว็บเบราว์เซอร์, มือถือ)

การเข้าถึง Keras

import tensorflow
from tensorflow import keras

Keras Functional API

Functional API ยืดหยุ่นกว่า Sequential API รองรับโมเดลที่มีโทโพโลยีไม่เชิงเส้น (Non-linear topology), แชร์เลเยอร์ (Shared layers), และหลาย Input/Output โมเดล Deep Learning ปกติเป็น Directed Acyclic Graph (DAG) ของเลเยอร์ Functional API ช่วยสร้างกราฟเลเยอร์นี้ได้

ตัวอย่าง: ดึงและนำโหนดกลาง (Intermediate nodes) ไปใช้ซ้ำ

print("VGG19 model with pre-trained weights")
vgg19 = tf.keras.applications.VGG19()
features_list = [layer.output for layer in vgg19.layers]
feat_extraction_model = keras.Model(inputs=vgg19.input, outputs=features_list)

img = np.random.random((1, 224, 224, 3)).astype("float32")
print("Create feature-extraction model")
extracted_features = feat_extraction_model(img)

Code credit: TensorFlow Keras Functional Guide

ผลลัพธ์

VGG19 model with pre-trained weights
Downloading data from https://storage.googleapis.com/tensorflow/kerasapplications/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels.h5
574717952/574710816 [==============================] - 6s 0us/step
Create feature-extraction model

คำอธิบาย

  • กราฟเลเยอร์เป็นโครงสร้างข้อมูลแบบคงที่ (Static) จึงเข้าถึงได้
  • โมเดล Functional จึงพล็อตเป็นภาพได้
  • Activation ของเลเยอร์กลาง (Nodes) เข้าถึงและนำไปใช้ซ้ำได้
  • มีประโยชน์มากสำหรับ Feature Extraction
  • ใช้โมเดล VGG19 ที่มี Pre-trained weights จาก ImageNet
  • Activation กลางได้จากการ Query กราฟข้อมูล
  • นำ Features ไปสร้าง Feature-extraction model ใหม่ที่คืนค่า Intermediate activations