Skip to content

Instantly share code, notes, and snippets.

@tomthetrainer
Created February 15, 2017 23:03
Show Gist options
  • Save tomthetrainer/bb5d9eece175ae12c467b58b5b85161d to your computer and use it in GitHub Desktop.
Save tomthetrainer/bb5d9eece175ae12c467b58b5b85161d to your computer and use it in GitHub Desktop.
Code from youtube video
import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
/**
* Created by tomhanlon on 2/10/17.
*/
public class ImportIris {
public static void main(String[] args) throws Exception {
// Keras model saved was a sequential model
// Use MultiLayerNetwork in Deeplearning4J when importing Sequential models
// Use Computationgraph for keras models built using Functional API
// Load the weights and config seperately
MultiLayerNetwork model = KerasModelImport.importKerasSequentialModelAndWeights("/tmp/iris_model_json", "/tmp/iris_model_weights");
// Load the weights and config from single file
MultiLayerNetwork model1 = KerasModelImport.importKerasSequentialModelAndWeights("/tmp/full_iris_model");
// DeepLearning4j equivalent of keras model.to_json()
System.out.print(model.conf().toJson());
// Our model expects input like this.
// [ 7.2 3. 5.8 1.6]
//4.6 3.6 1. 0.2
//5.1 3.5 1.4 0.2
//5.9 3. 5.1 1.8
INDArray myArray = Nd4j.zeros(1, 4); // one row 4 column array
myArray.putScalar(0,0, 4.6);
myArray.putScalar(0,1, 3.6);
myArray.putScalar(0,2, 1.0);
myArray.putScalar(0,3, 0.2);
INDArray output = model.output(myArray);
System.out.println("First Model Output");
System.out.println(myArray);
System.out.println(output);
INDArray output1 = model1.output(myArray);
System.out.println("Second Model Output");
System.out.println(myArray);
System.out.println(output1);
}
}
@tomthetrainer
Copy link
Author

tomthetrainer commented Feb 15, 2017

iris.py

import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.cross_validation import cross_val_score, KFold
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import Pipeline

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load dataset
dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:,0:4].astype(float)
Y = dataset[:,4]
print(X)
print(Y)

#encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
encoded_Y = encoder.transform(Y)


# convert integers to dummy variables (hot encoded)
dummy_y = np_utils.to_categorical(encoded_Y)
print(dummy_y)

# define baseline model
#def baseline_model():
# create model
model = Sequential()
model.add(Dense(4, input_dim=4, activation='relu'))
model.add(Dense(3,activation='sigmoid'))

# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

#    return model
#model.fit
model.fit(X, dummy_y, nb_epoch=200, batch_size=5)
prediction = model.predict(numpy.array([[4.6,3.6,1.0,0.2]]));
print(prediction);


model.save_weights('/tmp/iris_model_weights')
model.save('/tmp/full_iris_model')
json_string = model.to_json()
text_file = open("/tmp/iris_model_json", "w")
text_file.write(json_string)
text_file.close()

@tomthetrainer
Copy link
Author

Here is a version of the iris.csv file

https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv

Delete the first line !!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment