SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
LET US: GO 2017 FALL
WHY
You have just found Keras
• Francois Chollet
• API
• TesnsorFlow, Theano, CNTK
############################
###DNN in TensorFlow Only###
############################
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
###1. Load data set, and split it if necessary
mnist = input_data.read_data_sets("MNIST_data/")
###2. we create a holder, a container to place the computation activities in tensorflow
###identifying format and tensor's r/c, null means any kind
VISIBLE_NODES = 784
HIDDEN_NODES = 400
x = tf.placeholder("float", shape=[None, VISIBLE_NODES])
y = tf.placeholder("float", shape=[None, 10])
###3. We identify weights and biases with tensor shape, start with 0
weights = tf.Variable(tf.random_normal((VISIBLE_NODES, HIDDEN_NODES),
mean=0.0, stddev=1. / VISIBLE_NODES))
hidden_bias = tf.Variable(tf.zeros([HIDDEN_NODES]))
visible_bias = tf.Variable(tf.zeros([VISIBLE_NODES]))
###4. set up the sigmoid model and multiply x and W with matmul function, building the
###hidden layer and reconstruction layer
hidden_activation = tf.nn.sigmoid(tf.matmul(x, weights) + hidden_bias)
visible_reconstruction = tf.nn.sigmoid(tf.matmul(hidden_activation, tf.transpose(weights))
+ visible_bias)
final_hidden_activation = tf.nn.sigmoid(tf.matmul(visible_reconstruction, weights)
+ hidden_bias)
###5. This process can be understood as being two phases of learning
###positive and negative or, more poetically, waking and sleeping
positive_phase = tf.matmul(tf.transpose(x), hidden_activation)
negative_phase = tf.matmul(tf.transpose(visible_reconstruction), final_hidden_activation)
LEARNING_RATE = 0.01
weight_update = weights.assign_add(LEARNING_RATE *
(positive_phase - negative_phase))
visible_bias_update = visible_bias.assign_add(LEARNING_RATE *
tf.reduce_mean(x - visible_reconstruction, 0))
hidden_bias_update = hidden_bias.assign_add(LEARNING_RATE *
tf.reduce_mean(hidden_activation - final_hidden_activation, 0))
###6. Now we create the operations for scaling the hidden and visible biases, with loss
###function feedback
train_op = tf.group(weight_update, visible_bias_update, hidden_bias_update)
loss_op = tf.reduce_sum(tf.square(x - visible_reconstruction))
###7. We start the session
session = tf.Session()
session.run(tf.global_variables_initializer())
current_epochs = 0
###8.Run the session
for i in range(20):
total_loss = 0
while mnist.train.epochs_completed == current_epochs:
batch_inputs, batch_labels = mnist.train.next_batch(100)
_, reconstruction_loss = session.run([train_op, loss_op], feed_dict={input_placeholder: batch_inputs})
total_loss += reconstruction_loss
print("epochs %s loss %s" % (current_epochs, reconstruction_loss))
current_epochs = mnist.train.epochs_completed
##############################
###DNN in TensorFlow KeRas ###
##############################
###1. Load Data and Splot Data
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils import np_utils
(X_train, Y_train), (X_test, Y_test) = mnist.load_data()
###2.Preprocess
X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
classes = 10
Y_train = np_utils.to_categorical(Y_train, classes)
Y_test = np_utils.to_categorical(Y_test, classes)
###3. Set up parameters
input_size = 784
batch_size = 100
hidden_neurons = 400
epochs = 30
###4.Build the model
model = Sequential()
model.add(Dense(hidden_neurons, input_dim=input_size))
model.add(Activation('relu'))
model.add(Dense(classes, input_dim=hidden_neurons))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy',
metrics=['accuracy'], optimizer='adadelta')
model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1)
###5.Test
score = model.evaluate(X_test, Y_test, verbose=1)
print('n''Test accuracy:', score[1])
#Test accuracy: 0.983
VS
Keras
TensorFlow
https://charleshsliao.wordpress.com/2017/06/19/dnn-and-cnn-of-tensorflowkeras-with-mnist-data/
: https://tykimos.github.io/
𝒀 = 𝑤 × 𝑿 + 𝑏
𝒀 𝑤 𝑿 𝑏
𝒀 𝑤 𝑿 𝑏
𝑤 𝑏 !
𝒀 = 𝑤 × 𝑿 + 𝑏
𝑤 𝑏 !
: https://tykimos.github.io/
from keras.preprocessing.image import ImageDataGenerator
# 1.
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
‘handwriting_shape/train', //
target_size=(28, 28), //
batch_size=10, //
class_mode=‘categorical') //
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
# 2.
model = Sequential() //
model.add(Conv2D(32, // ??
kernel_size=(3, 3), // ??
activation=‘relu’, //
input_shape=(28, 28, 3)) // ( , )
model.add(Conv2D(64, (3, 3), activation=‘relu')) //
model.add(MaxPooling2D(pool_size=(2, 2))) // ??
model.add(Flatten()) // -> ??
model.add(Dense(128, activation=‘relu'))
model.add(Dense(4, activation='softmax'))
: https://tykimos.github.io/
: https://tykimos.github.io/
: https://tykimos.github.io/
: https://tykimos.github.io/
# 2.
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D
model = Sequential() //
model.add(Conv2D(32, //
kernel_size=(3, 3), //
activation=‘relu’, //
input_shape=(28, 28, 3)) // ( , )
model.add(Conv2D(64, (3, 3), activation=‘relu')) //
model.add(MaxPooling2D(pool_size=(2, 2))) //
model.add(Flatten()) // ->
model.add(Dense(128, activation=‘relu’)) //
model.add(Dense(4, activation=‘softmax')) //
# 3.
model.compile(loss='categorical_crossentropy',
optimizer='adam', metrics=[‘accuracy']) //
# 4.
model.fit_generator(
train_generator, //
steps_per_epoch=30, // / (=300/10)
epochs=150) //
# 5.
score=model.evaluate_generator(test_generator, steps=3)
# 6. coreml
import coremltools
coreml_model = coremltools.converters.keras.convert(model,
input_names=‘image’, // =
output_names=‘class',
image_input_names = ‘image',
class_labels = ['circle', 'rectangle', ‘triangle'], //
is_bgr=True)
coreml_model.save(‘shape_detect_with_keras.mlmodel') //
# 7. coreml
import CoreML
let model = shape_detect_with_keras()
guard let output: shape_detect_with_kerasOutput =
try? model.prediction(image: image) else { return }
You have just found Keras
https://github.com/MijeongJeon/ShapeDetector_Keras_CoreML/
ninevincentg@gmail.com

Contenu connexe

Similaire à 프알못의 Keras 사용기

iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남Mijeong Jeon
 
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...Databricks
 
TensorFlow example for AI Ukraine2016
TensorFlow example  for AI Ukraine2016TensorFlow example  for AI Ukraine2016
TensorFlow example for AI Ukraine2016Andrii Babii
 
Introduction To Using TensorFlow & Deep Learning
Introduction To Using TensorFlow & Deep LearningIntroduction To Using TensorFlow & Deep Learning
Introduction To Using TensorFlow & Deep Learningali alemi
 
slide-keras-tf.pptx
slide-keras-tf.pptxslide-keras-tf.pptx
slide-keras-tf.pptxRithikRaj25
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APIMr. Vengineer
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowAndrew Ferlitsch
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Databricks
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlowOswald Campesato
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Ganesan Narayanasamy
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3Max Kleiner
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfactexerode
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torchRiza Fahmi
 
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...Edureka!
 
GANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfGANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfVivekanandaGN1
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnnDebarko De
 

Similaire à 프알못의 Keras 사용기 (20)

iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
 
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
A Tale of Three Deep Learning Frameworks: TensorFlow, Keras, & PyTorch with B...
 
TensorFlow example for AI Ukraine2016
TensorFlow example  for AI Ukraine2016TensorFlow example  for AI Ukraine2016
TensorFlow example for AI Ukraine2016
 
Introduction To Using TensorFlow & Deep Learning
Introduction To Using TensorFlow & Deep LearningIntroduction To Using TensorFlow & Deep Learning
Introduction To Using TensorFlow & Deep Learning
 
slide-keras-tf.pptx
slide-keras-tf.pptxslide-keras-tf.pptx
slide-keras-tf.pptx
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network APITensorFlow Lite (r1.5) & Android 8.1 Neural Network API
TensorFlow Lite (r1.5) & Android 8.1 Neural Network API
 
Keras and TensorFlow
Keras and TensorFlowKeras and TensorFlow
Keras and TensorFlow
 
Machine Learning - Introduction to Tensorflow
Machine Learning - Introduction to TensorflowMachine Learning - Introduction to Tensorflow
Machine Learning - Introduction to Tensorflow
 
Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0Introduction to TensorFlow 2.0
Introduction to TensorFlow 2.0
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117Power ai tensorflowworkloadtutorial-20171117
Power ai tensorflowworkloadtutorial-20171117
 
Neural networks using tensor flow in amazon deep learning server
Neural networks using tensor flow in amazon deep learning serverNeural networks using tensor flow in amazon deep learning server
Neural networks using tensor flow in amazon deep learning server
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdfNeed an detailed analysis of what this code-model is doing- Thanks #St.pdf
Need an detailed analysis of what this code-model is doing- Thanks #St.pdf
 
Machine learning with py torch
Machine learning with py torchMachine learning with py torch
Machine learning with py torch
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...
Introduction To TensorFlow | Deep Learning with TensorFlow | TensorFlow For B...
 
GANS Project for Image idetification.pdf
GANS Project for Image idetification.pdfGANS Project for Image idetification.pdf
GANS Project for Image idetification.pdf
 
Image classification using cnn
Image classification using cnnImage classification using cnn
Image classification using cnn
 

Plus de Mijeong Jeon

Azure_CogSearch_OAI.pdf
Azure_CogSearch_OAI.pdfAzure_CogSearch_OAI.pdf
Azure_CogSearch_OAI.pdfMijeong Jeon
 
Performance Comparing : ONNX, TF, PyTorch
Performance Comparing : ONNX, TF, PyTorchPerformance Comparing : ONNX, TF, PyTorch
Performance Comparing : ONNX, TF, PyTorchMijeong Jeon
 
let us: Go! 2019 Summer 앱 수익으로 월세내기
let us: Go! 2019 Summer 앱 수익으로 월세내기let us: Go! 2019 Summer 앱 수익으로 월세내기
let us: Go! 2019 Summer 앱 수익으로 월세내기Mijeong Jeon
 
Azure AutoML 함께 실습하기
Azure AutoML 함께 실습하기Azure AutoML 함께 실습하기
Azure AutoML 함께 실습하기Mijeong Jeon
 
iOS 모바일에서 한글 손글씨 인식하기(with Keras)
iOS 모바일에서 한글 손글씨 인식하기(with Keras) iOS 모바일에서 한글 손글씨 인식하기(with Keras)
iOS 모바일에서 한글 손글씨 인식하기(with Keras) Mijeong Jeon
 
내 손 위의 딥러닝_iOS에 딥러닝 심기
내 손 위의 딥러닝_iOS에 딥러닝 심기 내 손 위의 딥러닝_iOS에 딥러닝 심기
내 손 위의 딥러닝_iOS에 딥러닝 심기 Mijeong Jeon
 
프알못의 Realm 사용기
프알못의 Realm 사용기프알못의 Realm 사용기
프알못의 Realm 사용기Mijeong Jeon
 

Plus de Mijeong Jeon (8)

Azure_CogSearch_OAI.pdf
Azure_CogSearch_OAI.pdfAzure_CogSearch_OAI.pdf
Azure_CogSearch_OAI.pdf
 
Performance Comparing : ONNX, TF, PyTorch
Performance Comparing : ONNX, TF, PyTorchPerformance Comparing : ONNX, TF, PyTorch
Performance Comparing : ONNX, TF, PyTorch
 
let us: Go! 2019 Summer 앱 수익으로 월세내기
let us: Go! 2019 Summer 앱 수익으로 월세내기let us: Go! 2019 Summer 앱 수익으로 월세내기
let us: Go! 2019 Summer 앱 수익으로 월세내기
 
Azure AutoML 함께 실습하기
Azure AutoML 함께 실습하기Azure AutoML 함께 실습하기
Azure AutoML 함께 실습하기
 
iOS 모바일에서 한글 손글씨 인식하기(with Keras)
iOS 모바일에서 한글 손글씨 인식하기(with Keras) iOS 모바일에서 한글 손글씨 인식하기(with Keras)
iOS 모바일에서 한글 손글씨 인식하기(with Keras)
 
180825 azure ai
180825 azure ai180825 azure ai
180825 azure ai
 
내 손 위의 딥러닝_iOS에 딥러닝 심기
내 손 위의 딥러닝_iOS에 딥러닝 심기 내 손 위의 딥러닝_iOS에 딥러닝 심기
내 손 위의 딥러닝_iOS에 딥러닝 심기
 
프알못의 Realm 사용기
프알못의 Realm 사용기프알못의 Realm 사용기
프알못의 Realm 사용기
 

Dernier

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 

Dernier (20)

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 

프알못의 Keras 사용기

  • 1. LET US: GO 2017 FALL
  • 2. WHY
  • 3.
  • 4. You have just found Keras
  • 5.
  • 6. • Francois Chollet • API • TesnsorFlow, Theano, CNTK
  • 7. ############################ ###DNN in TensorFlow Only### ############################ import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data ###1. Load data set, and split it if necessary mnist = input_data.read_data_sets("MNIST_data/") ###2. we create a holder, a container to place the computation activities in tensorflow ###identifying format and tensor's r/c, null means any kind VISIBLE_NODES = 784 HIDDEN_NODES = 400 x = tf.placeholder("float", shape=[None, VISIBLE_NODES]) y = tf.placeholder("float", shape=[None, 10]) ###3. We identify weights and biases with tensor shape, start with 0 weights = tf.Variable(tf.random_normal((VISIBLE_NODES, HIDDEN_NODES), mean=0.0, stddev=1. / VISIBLE_NODES)) hidden_bias = tf.Variable(tf.zeros([HIDDEN_NODES])) visible_bias = tf.Variable(tf.zeros([VISIBLE_NODES])) ###4. set up the sigmoid model and multiply x and W with matmul function, building the ###hidden layer and reconstruction layer hidden_activation = tf.nn.sigmoid(tf.matmul(x, weights) + hidden_bias) visible_reconstruction = tf.nn.sigmoid(tf.matmul(hidden_activation, tf.transpose(weights)) + visible_bias) final_hidden_activation = tf.nn.sigmoid(tf.matmul(visible_reconstruction, weights) + hidden_bias) ###5. This process can be understood as being two phases of learning ###positive and negative or, more poetically, waking and sleeping positive_phase = tf.matmul(tf.transpose(x), hidden_activation) negative_phase = tf.matmul(tf.transpose(visible_reconstruction), final_hidden_activation) LEARNING_RATE = 0.01 weight_update = weights.assign_add(LEARNING_RATE * (positive_phase - negative_phase)) visible_bias_update = visible_bias.assign_add(LEARNING_RATE * tf.reduce_mean(x - visible_reconstruction, 0)) hidden_bias_update = hidden_bias.assign_add(LEARNING_RATE * tf.reduce_mean(hidden_activation - final_hidden_activation, 0)) ###6. Now we create the operations for scaling the hidden and visible biases, with loss ###function feedback train_op = tf.group(weight_update, visible_bias_update, hidden_bias_update) loss_op = tf.reduce_sum(tf.square(x - visible_reconstruction)) ###7. We start the session session = tf.Session() session.run(tf.global_variables_initializer()) current_epochs = 0 ###8.Run the session for i in range(20): total_loss = 0 while mnist.train.epochs_completed == current_epochs: batch_inputs, batch_labels = mnist.train.next_batch(100) _, reconstruction_loss = session.run([train_op, loss_op], feed_dict={input_placeholder: batch_inputs}) total_loss += reconstruction_loss print("epochs %s loss %s" % (current_epochs, reconstruction_loss)) current_epochs = mnist.train.epochs_completed ############################## ###DNN in TensorFlow KeRas ### ############################## ###1. Load Data and Splot Data from keras.datasets import mnist from keras.models import Sequential from keras.layers.core import Dense, Activation from keras.utils import np_utils (X_train, Y_train), (X_test, Y_test) = mnist.load_data() ###2.Preprocess X_train = X_train.reshape(60000, 784) X_test = X_test.reshape(10000, 784) X_train = X_train.astype('float32') X_test = X_test.astype('float32') X_train /= 255 X_test /= 255 classes = 10 Y_train = np_utils.to_categorical(Y_train, classes) Y_test = np_utils.to_categorical(Y_test, classes) ###3. Set up parameters input_size = 784 batch_size = 100 hidden_neurons = 400 epochs = 30 ###4.Build the model model = Sequential() model.add(Dense(hidden_neurons, input_dim=input_size)) model.add(Activation('relu')) model.add(Dense(classes, input_dim=hidden_neurons)) model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adadelta') model.fit(X_train, Y_train, batch_size=batch_size, epochs=epochs, verbose=1) ###5.Test score = model.evaluate(X_test, Y_test, verbose=1) print('n''Test accuracy:', score[1]) #Test accuracy: 0.983 VS Keras TensorFlow https://charleshsliao.wordpress.com/2017/06/19/dnn-and-cnn-of-tensorflowkeras-with-mnist-data/
  • 8. : https://tykimos.github.io/ 𝒀 = 𝑤 × 𝑿 + 𝑏 𝒀 𝑤 𝑿 𝑏 𝒀 𝑤 𝑿 𝑏 𝑤 𝑏 !
  • 9. 𝒀 = 𝑤 × 𝑿 + 𝑏 𝑤 𝑏 ! : https://tykimos.github.io/
  • 10.
  • 11.
  • 12.
  • 13. from keras.preprocessing.image import ImageDataGenerator # 1. train_datagen = ImageDataGenerator(rescale=1./255) train_generator = train_datagen.flow_from_directory( ‘handwriting_shape/train', // target_size=(28, 28), // batch_size=10, // class_mode=‘categorical') //
  • 14. from keras.models import Sequential from keras.layers import Dense, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D # 2. model = Sequential() // model.add(Conv2D(32, // ?? kernel_size=(3, 3), // ?? activation=‘relu’, // input_shape=(28, 28, 3)) // ( , ) model.add(Conv2D(64, (3, 3), activation=‘relu')) // model.add(MaxPooling2D(pool_size=(2, 2))) // ?? model.add(Flatten()) // -> ?? model.add(Dense(128, activation=‘relu')) model.add(Dense(4, activation='softmax'))
  • 19. # 2. from keras.models import Sequential from keras.layers import Dense, Flatten from keras.layers.convolutional import Conv2D, MaxPooling2D model = Sequential() // model.add(Conv2D(32, // kernel_size=(3, 3), // activation=‘relu’, // input_shape=(28, 28, 3)) // ( , ) model.add(Conv2D(64, (3, 3), activation=‘relu')) // model.add(MaxPooling2D(pool_size=(2, 2))) // model.add(Flatten()) // -> model.add(Dense(128, activation=‘relu’)) // model.add(Dense(4, activation=‘softmax')) //
  • 20. # 3. model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=[‘accuracy']) // # 4. model.fit_generator( train_generator, // steps_per_epoch=30, // / (=300/10) epochs=150) // # 5. score=model.evaluate_generator(test_generator, steps=3)
  • 21. # 6. coreml import coremltools coreml_model = coremltools.converters.keras.convert(model, input_names=‘image’, // = output_names=‘class', image_input_names = ‘image', class_labels = ['circle', 'rectangle', ‘triangle'], // is_bgr=True) coreml_model.save(‘shape_detect_with_keras.mlmodel') //
  • 22. # 7. coreml import CoreML let model = shape_detect_with_keras() guard let output: shape_detect_with_kerasOutput = try? model.prediction(image: image) else { return }
  • 23. You have just found Keras
  • 24.
  • 25.
  • 26.
  • 27.