In [1]:
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from keras.models import Sequential
from keras import layers
import numpy as np
In [2]:
dataset = pd.read_csv("Iris.csv")
In [3]:
dataset.head()
Out[3]:
In [4]:
dataset.info()
In [6]:
dataset["Species"].sum()
Out[6]:
In [7]:
train_data = dataset[["SepalLengthCm", "SepalWidthCm", "PetalLengthCm", "PetalWidthCm"]]
train_labels = dataset[["Species"]]
In [8]:
train_data.shape
Out[8]:
In [9]:
train_labels.shape
Out[9]:
In [10]:
train_data.head()
Out[10]:
In [11]:
mean = np.mean(train_data)
std = np.std(train_data)
In [12]:
train_data -= mean
train_data /= std
In [13]:
train_data.head()
Out[13]:
In [14]:
train_labels.head()
Out[14]:
In [15]:
encoder = LabelEncoder()
encoder.fit(train_labels)
encoded_labels = encoder.transform(train_labels)
In [16]:
encoded_labels
Out[16]:
In [17]:
def vectorize_data(values, dimension = 3):
results = np.zeros((len(values), dimension))
for i, value in enumerate(values):
results[i, value] = 1.
return results
In [18]:
labels = vectorize_data(encoded_labels)
In [19]:
labels[57]
Out[19]:
In [20]:
train_data.shape
Out[20]:
In [21]:
labels.shape
Out[21]:
In [22]:
x_train = train_data[:140]
x_test = train_data[140:]
train_labs = labels[:140]
test_labs = labels[140:]
In [23]:
x_train.shape
Out[23]:
In [24]:
x_test.shape
Out[24]:
In [25]:
def build_neural_network():
nn = Sequential()
nn.add(layers.Dense(64, activation = "relu", input_shape = (x_train.shape[1], )))
nn.add(layers.Dense(64, activation = "relu"))
nn.add(layers.Dense(3, activation = "softmax"))
nn.compile(loss = "categorical_crossentropy", optimizer = "rmsprop", metrics = ["accuracy"])
return nn
In [26]:
x_train = np.array(x_train)
x_test = np.array(x_test)
train_labs = np.array(train_labs)
test_labs = np.array(test_labs)
In [27]:
x_train[0]
Out[27]:
In [28]:
model = build_neural_network()
In [39]:
history = model.fit(x_train, train_labs, epochs = 100)
In [41]:
type(history)
Out[41]:
In [42]:
results = history.history
In [44]:
results.keys()
Out[44]:
In [45]:
import matplotlib.pyplot as plt
In [46]:
epochs = range(1, 101)
train_loss = results["loss"]
plt.plot(epochs, train_loss, 'b')
plt.xlabel("Epochs")
plt.ylabel("loss")
plt.title("Training loss")
plt.show()
In [ ]: