-
Notifications
You must be signed in to change notification settings - Fork 1
/
mlp.py
101 lines (68 loc) · 2.43 KB
/
mlp.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# -*- coding: utf-8 -*-
"""MLP.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ew5OnCdZdu7TAEUfn4QYA8w6lrB7vfF-
# Imports and Setup
"""
# download dependencies
!pip install tensorflow numpy pandas keras
# imports
import numpy as np
from tensorflow.keras import optimizers
from keras import models
from keras import layers
from tensorflow.keras.utils import to_categorical
from sklearn import datasets
from sklearn.model_selection import train_test_split
"""# Load Data
## Find Dataset Here:
https://www.kaggle.com/datasets/arshid/iris-flower-dataset?select=IRIS.csv
"""
# load the dataset
iris_dataset = datasets.load_iris()
# multiply all indicies by 10 and convert to int type
# conversion is required since the digital circuit takes in integers as input
for num in iris_dataset['data']:
num *= 10
iris_dataset['data'] = iris_dataset['data'].astype(int)
X = iris_dataset.data
y = iris_dataset.target
# dataset format
iris_dataset
"""# Defining the Model"""
# define a sequential model
network = models.Sequential()
# the implemented MLP structure:
# 1 input layer
# 1 hidden layer with 3 neurons
# 1 output layer
network.add(layers.Dense(3, activation='sigmoid', input_shape=(4,)))
"""# Compiling the Model"""
# adam optimizer
adam_optimizer = optimizers.Adam(learning_rate=0.1)
network.compile(optimizer=adam_optimizer,
loss='categorical_crossentropy',
metrics=['accuracy'])
# model object
network
"""# Separating Training and Testing Data"""
# split data into train batch and test batch
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
# convert labels to integer categorical data
train_labels = to_categorical(y_train).astype(int)
test_labels = to_categorical(y_test).astype(int)
"""# Training the Model"""
# checks if model is saved to prevent retraining
try:
network = models.load_model('/content/sample_data/mlp')
except:
network.fit(X_train, train_labels, epochs=20, batch_size=1)
"""# Evaluating the Model with Test Data"""
# evaluation metrics
test_loss, test_acc = network.evaluate(X_test, test_labels)
"""# Save the model"""
# save the model
network.save('/content/sample_data/mlp')
# extract weight data and convert to integer type to be inputted into the digital circuit
for layer in network.layers: print(layer.get_weights()[0].astype(int), layer.get_weights()[1].astype(int))