# k-Fold Cross-Validating Neural Networks

If we have smaller data it can be useful to benefit from k-fold cross-validation to maximize our ability to evaluate the neural network’s performance. This is possible in Keras because we can “wrap” any neural network such that it can use the evaluation features available in scikit-learn, including k-fold cross-validation. To accomplish this, we first have to create a function that returns a compiled neural network. Next we use `KerasClassifier`

(if we have a classifier, if we have a regressor we can use `KerasRegressor`

) to wrap the model so it can be used by scikit-learn. After this, we can use our neural network like any other scikit-learn learning algorithm (e.g. random forests, logistic regression). In our solution, we used `cross_val_score`

to run a 3-fold cross-validation on our neural network.

## Preliminaries

```
/* Load libraries */
import numpy as np
from keras import models
from keras import layers
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import make_classification
/* Set random seed */
np.random.seed(0)
```

```
Using TensorFlow backend.
```

## Create Feature And Target Data

```
/* Number of features */
number_of_features = 100
/* Generate features matrix and target vector */
features, target = make_classification(n_samples = 10000,
n_features = number_of_features,
n_informative = 3,
n_redundant = 0,
n_classes = 2,
weights = [.5, .5],
random_state = 0)
```

## Create Function That Constructs Neural Network

```
/* Create function returning a compiled network */
def create_network():
/* Start neural network */
network = models.Sequential()
/* Add fully connected layer with a ReLU activation function */
network.add(layers.Dense(units=16, activation='relu', input_shape=(number_of_features,)))
/* Add fully connected layer with a ReLU activation function */
network.add(layers.Dense(units=16, activation='relu'))
/* Add fully connected layer with a sigmoid activation function */
network.add(layers.Dense(units=1, activation='sigmoid'))
/* Compile neural network */
network.compile(loss='binary_crossentropy', /* Cross-entropy */
optimizer='rmsprop', /* Root Mean Square Propagation */
metrics=['accuracy']) /* Accuracy performance metric */
/* Return compiled network */
return network
```

## Wrap Function In KerasClassifier

```
/* Wrap Keras model so it can be used by scikit-learn */
neural_network = KerasClassifier(build_fn=create_network,
epochs=10,
batch_size=100,
verbose=0)
```

## Conduct k-Fold Cross-Validation Using scikit-learn

```
/* Evaluate neural network using three-fold cross-validation */
cross_val_score(neural_network, features, target, cv=3)
```

`array([ 0.90491901, 0.77827782, 0.87038704])`

# Python Example for Beginners

## Two Machine Learning Fields

There are two sides to machine learning:

**Practical Machine Learning:**This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.**Theoretical Machine Learning**: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

**Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes**

**Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!**

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

**Applied Statistics with R for Beginners and Business Professionals**

**Data Science and Machine Learning Projects in Python: Tabular Data Analytics**

**Data Science and Machine Learning Projects in R: Tabular Data Analytics**

**Python Machine Learning & Data Science Recipes: Learn by Coding**

**R Machine Learning & Data Science Recipes: Learn by Coding**

**Comparing Different Machine Learning Algorithms in Python for Classification (FREE)**

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.The information presented here could also be found in public knowledge domains.

**Google –> SETScholars**

A list of Python, R and SQL Codes for Applied Machine Learning and Data Science at **https://setscholars.net/**Learn by Coding Categories:

- Classification:
**https://setscholars.net/category/classification/** - Data Analytics:
**https://setscholars.net/category/data-analytics/** - Data Science:
**https://setscholars.net/category/data-science/** - Data Visualisation:
**https://setscholars.net/category/data-visualisation/** - Machine Learning Recipe:
**https://setscholars.net/category/machine-learning-recipe/** - Pandas:
**https://setscholars.net/category/pandas/** - Python:
**https://setscholars.net/category/python/** - SKLEARN:
**https://setscholars.net/category/sklearn/** - Supervised Learning:
**https://setscholars.net/category/supervised-learning/** - Tabular Data Analytics:
**https://setscholars.net/category/tabular-data-analytics/** - End-to-End Data Science Recipes:
**https://setscholars.net/category/a-star-data-science-recipe/** - Applied Statistics:
**https://setscholars.net/category/applied-statistics/** - Bagging Ensemble:
**https://setscholars.net/category/bagging-ensemble/** - Boosting Ensemble:
**https://setscholars.net/category/boosting-ensemble/** - CatBoost:
**https://setscholars.net/category/catboost/** - Clustering:
**https://setscholars.net/category/clustering/** - Data Analytics:
**https://setscholars.net/category/data-analytics/** - Data Science:
**https://setscholars.net/category/data-science/** - Data Visualisation:
**https://setscholars.net/category/data-visualisation/** - Decision Tree:
**https://setscholars.net/category/decision-tree/** - LightGBM:
**https://setscholars.net/category/lightgbm/** - Machine Learning Recipe:
**https://setscholars.net/category/machine-learning-recipe/** - Multi-Class Classification:
**https://setscholars.net/category/multi-class-classification/** - Neural Networks:
**https://setscholars.net/category/neural-networks/** - Python Machine Learning:
**https://setscholars.net/category/python-machine-learning/** - Python Machine Learning Crash Course:
**https://setscholars.net/category/python-machine-learning-crash-course/** - R Classification:
**https://setscholars.net/category/r-classification/** - R for Beginners:
**https://setscholars.net/category/r-for-beginners/** - R for Business Analytics:
**https://setscholars.net/category/r-for-business-analytics/** - R for Data Science:
**https://setscholars.net/category/r-for-data-science/** - R for Data Visualisation:
**https://setscholars.net/category/r-for-data-visualisation/** - R for Excel Users:
**https://setscholars.net/category/r-for-excel-users/** - R Machine Learning:
**https://setscholars.net/category/r-machine-learning/** - R Machine Learning Crash Course:
**https://setscholars.net/category/r-machine-learning-crash-course/** - R Regression:
**https://setscholars.net/category/r-regression/** - Regression:
**https://setscholars.net/category/regression/** - XGBOOST:
**https://setscholars.net/category/xgboost/** - Excel examples for beginners:
**https://setscholars.net/category/excel-examples-for-beginners/** - C Programming tutorials & examples:
**https://setscholars.net/category/c-programming-tutorials/** - Javascript tutorials & examples:
**https://setscholars.net/category/javascript-tutorials-and-examples/** - Python tutorials & examples:
**https://setscholars.net/category/python-tutorials/** - R tutorials & examples:
**https://setscholars.net/category/r-for-beginners/** - SQL tutorials & examples:
**https://setscholars.net/category/sql-tutorials-for-business-analyst/**

**FREE downloadable Mathematics Worksheet for Kids**)

- Year 1 Mathematics Worksheet:
**https://setscholars.net/category/year-1-mathematics-worksheet/**