Skip to content

Instantly share code, notes, and snippets.

@angelormrl
Created May 12, 2019 20:58
Show Gist options
  • Save angelormrl/52d47294f6017f024bb0409fc32ab6ee to your computer and use it in GitHub Desktop.
Save angelormrl/52d47294f6017f024bb0409fc32ab6ee to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"from sklearn import datasets\n",
"from sklearn.neural_network import MLPClassifier"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"def normalize_data(x):\n",
" data = zeros(shape(x))\n",
" for i in range(len(x[0])):\n",
" feature = [example[i] for example in x]\n",
" max_val = np.max(feature)\n",
" min_val = np.min(feature)\n",
" val_range = max_val - min_val\n",
" for j in range(len(x)):\n",
" data[j][i] = (x[j][i] - min_val) / val_range\n",
" return data\n",
"\n",
"def accuracy_score(pred, true):\n",
" correct = np.sum(pred==true)\n",
" accuracy = correct/len(pred)\n",
" return accuracy"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0.93\n",
"[1 2 1 2 1 1 2 0 0 1 2 2 1 2 2 0 1 0 1 0 1 2 1 2 2 1 0 0 1 0 1 2 2 1 2 0 0\n",
" 1 1 0 2 0 2 1 2 0 2 2 1 0 0 1 1 0 1 2 0 1 1 0 2 0 1 2 1 2 2 0 0 1 2 0 2 2\n",
" 1 0 0 0 0 1 1 0 0 0 1 1 0 0 0 2 2 0 1 2 0 1 1 0 0 1]\n"
]
}
],
"source": [
"iris = datasets.load_iris()\n",
"X = iris.data # we only take the first two features.\n",
"y = iris.target\n",
"\n",
"normX = normalize_data(X)\n",
"\n",
"indices = np.random.permutation(len(normX))\n",
"\n",
"train, test = indices[100:], indices[:100]\n",
"\n",
"net = MLPClassifier(activation='logistic', hidden_layer_sizes=(5), learning_rate_init=0.01)\n",
"\n",
"net.fit(normX[train], y[train])\n",
"\n",
"preds = net.predict(normX[test])\n",
"\n",
"accuracy = accuracy_score(preds, y[test])\n",
"print(accuracy)\n",
"print(preds)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.14"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment