---
title: "Building a simple neural network using Python Keras and Tensorflow"
author: "Prof. Eric A. Suess"
format: 
  html:
    embed-resources: true
---

**Update:** Using Python Keras and TensorFlow.

Thank you

A big thank you to Leon Jessen for posting his code on github.

[Building a simple neural network using Keras and Tensorflow](https://github.com/leonjessen/keras_tensorflow_on_iris/blob/master/README.md)

I have forked his project on github and put his code into an R Notebook so we can run it in class.

### Motivation

The following is a minimal example for building your first simple artificial neural network using Keras and TensorFlow for Python.

[TensorFlow](https://keras.io/).

### Gettings started - Install Keras and TensorFlow for R

You can install the Keras for R package from CRAN as follows:

You can install the Keras for R package from CRAN as follows:

```{python}
from sklearn import datasets
from sklearn.model_selection import train_test_split
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
```

### Load the Iris dataset

```{python}
# Load iris dataset
iris = datasets.load_iris()
X = iris.data[:, :4]  # We only take the first four features.
y = iris.target

# Print the first 5 rows of the iris data
print(X[:5])

# Print the first 5 rows of the iris target
print(y[:5])
```

### Split the data into training and test sets

```{python}
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```

Build one layer neural network with 10 nodes to classify the type of iris flowers using the iris dataset

```{python}
model = Sequential([
    Dense(10, activation='relu', input_shape=(4,)),
    Dense(3, activation='softmax')
])
```

### Compile the model

```{python}
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
```

### Train the model

```{python}
model.fit(X_train, y_train, epochs=200)
```

### Evaluate the model

```{python}
print("Model Accuracy:", model.evaluate(X_test, y_test)[1])
```

### Predict the model

```{python}
predictions = model.predict(X_test)
print(np.argmax(predictions, axis=1))
```

### Confusion matrix

```{python}
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt

cm = confusion_matrix(y_test, np.argmax(predictions, axis=1))
plt.imshow(cm, cmap='binary')
plt.show()
```

### Summary

In this post, we learned how to build a simple neural network using Keras and TensorFlow for R. We used the iris dataset to classify the type of iris flowers. We built a one-layer neural network with 10 nodes and used the ReLU activation function. We compiled the model using the Adam optimizer and sparse categorical cross-entropy loss function. We trained the model for 100 epochs and evaluated the model using the test data. Finally, we made predictions using the model and printed the predicted classes.



