jupyter files

This commit is contained in:
mhjensen
2018-05-06 22:19:59 -04:00
parent c497ee89f2
commit 11d2a0f8fc
38 changed files with 9017 additions and 0 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,82 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: 'src/Hudson_Bay.csv'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-2-7c0c8f9a022b>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;31m# Load in data file\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mloadtxt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'src/Hudson_Bay.csv'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdelimiter\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;34m','\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mskiprows\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 13\u001b[0m \u001b[0;31m# Make arrays containing x-axis and hares and lynx populations\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0myear\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;32m/anaconda3/lib/python3.6/site-packages/numpy/lib/npyio.py\u001b[0m in \u001b[0;36mloadtxt\u001b[0;34m(fname, dtype, comments, delimiter, converters, skiprows, usecols, unpack, ndmin)\u001b[0m\n\u001b[1;32m 896\u001b[0m \u001b[0mfh\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfname\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'U'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 897\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 898\u001b[0;31m \u001b[0mfh\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mopen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 899\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 900\u001b[0m \u001b[0mfh\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'src/Hudson_Bay.csv'"
]
}
],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"from scipy import sparse\n",
"import pandas as pd\n",
"from IPython.display import display\n",
"import mglearn\n",
"import sklearn\n",
"from sklearn.linear_model import LinearRegression\n",
"from sklearn.tree import DecisionTreeRegressor\n",
"\n",
"# Load in data file\n",
"data = np.loadtxt('src/Hudson_Bay.csv', delimiter=',', skiprows=1)\n",
"# Make arrays containing x-axis and hares and lynx populations\n",
"#How do you import this data to IPython? Ask Morten\n",
"year = data[:,0]\n",
"hares = data[:,1]\n",
"lynx = data[:,2]\n",
"\n",
"plt.plot(year, hares ,'b-+', year, lynx, 'r-o')\n",
"plt.axis([1900,1920,0, 100.0])\n",
"plt.xlabel(r'Year')\n",
"plt.ylabel(r'Numbers of hares and lynx ')\n",
"plt.legend(('Hares','Lynx'), loc='upper right')\n",
"plt.title(r'Population of hares and lynx from 1900-1920 (x1000)}')\n",
"plt.savefig('Hudson_Bay_data.pdf')\n",
"plt.savefig('Hudson_Bay_data.png')\n",
"plt.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,270 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import random\n",
"class Network(object):\n",
" \n",
" def _init_(self, sizes):\n",
" self.num_layers=len(sizes)\n",
" self.sizes=sizes\n",
" self.biases=[np.random.randn(y,1) for y in sizes[1:]]\n",
" self.weights=[np.random.randn(y,x) for x,y in zip(sizes[:-1], sizes[1:])]\n",
"\n",
"#sizes is the number of neurons in each layer\n",
"#for example, say n_1st_layer=3, n_2nd_layer=3, n_3rd_layer=1, then net=Network([3,3,1])\n",
"\n",
"#The biases and weights are initialized randomly, using Gaussian distributions of mean=0, stdev=1\n",
"#z is a vector (or a np.array)\n",
"\n",
" def feedforward(self,a):\n",
" #returns output w/ 'a' as an input\n",
" for b, w in zip(self.biases, self.weights):\n",
" a=sigmoid(np.dot(w,b)+b)\n",
" return a\n",
" \n",
"#Apply a Stochastic Gradient Descent (SGD) method:\n",
" def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):\n",
" \"\"\"Trains network using batches incorporating SGD. The network will be evaluated against the\n",
" test data after each epoch, with partial progress being printed out (this is useful for tracking,\n",
" but slows the process.)\"\"\"\n",
" if test_data: n_test=len(test_data)\n",
" n=len(training_data)\n",
" for j in xrange(epochs):\n",
" random.shuffle(training_data)\n",
" mini_batches=[training_data[k:k+mini_batch_size] for k in xrange(o,n,mini_batch_size)]\n",
" for mini_batch in mini_batches:\n",
" self.update_mini_batch(mini_batch, eta)\n",
" if test_data:\n",
" print (\"Epoch {0}: {1}/{2}\".format(j, self.evaluate(test_data), n_test))\n",
" else:\n",
" print (\"Epoch {0} complete\".format(j))\n",
" \n",
" \n",
" def update_mini_batch(self, mini_batch, eta):\n",
" #updates w and b using backpropagation to a single mini batch. eta is the learning rate.\"\n",
" nabla_b=[np.zeros(b.shape) for b in self.biases]\n",
" nabla_w=[np.zeros(w.shape) for w in self.weights]\n",
" for x,y in mini_batch:\n",
" delta_nabla_b, delta_nabla_w=self.backprop(x,y)\n",
" nabla_b=[nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]\n",
" nabla_w=[nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]\n",
" self.weights=[w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)]\n",
" self.biases=[b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)]\n",
" \n",
" def backprop(self, x, y):\n",
" \"\"\"Return a tuple ``(nabla_b, nabla_w)`` representing the\n",
" gradient for the cost function C_x. ``nabla_b`` and\n",
" ``nabla_w`` are layer-by-layer lists of numpy arrays, similar\n",
" to ``self.biases`` and ``self.weights``.\"\"\"\n",
" nabla_b = [np.zeros(b.shape) for b in self.biases]\n",
" nabla_w = [np.zeros(w.shape) for w in self.weights]\n",
" # feedforward\n",
" activation = x\n",
" activations = [x] # list to store all the activations, layer by layer\n",
" zs = [] # list to store all the z vectors, layer by layer\n",
" for b, w in zip(self.biases, self.weights):\n",
" z = np.dot(w, activation)+b\n",
" zs.append(z)\n",
" activation = sigmoid(z)\n",
" activations.append(activation)\n",
" # backward pass\n",
" delta = self.cost_derivative(activations[-1], y) * \\\n",
" sigmoid_prime(zs[-1])\n",
" nabla_b[-1] = delta\n",
" nabla_w[-1] = np.dot(delta, activations[-2].transpose())\n",
" # Note that the variable l in the loop below is used a little\n",
" # differently to the notation in Chapter 2 of the book. Here,\n",
" # l = 1 means the last layer of neurons, l = 2 is the\n",
" # second-last layer, and so on. It's a renumbering of the\n",
" # scheme in the book, used here to take advantage of the fact\n",
" # that Python can use negative indices in lists.\n",
" for l in xrange(2, self.num_layers):\n",
" z = zs[-l]\n",
" sp = sigmoid_prime(z)\n",
" delta = np.dot(self.weights[-l+1].transpose(), delta) * sp\n",
" nabla_b[-l] = delta\n",
" nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())\n",
" return (nabla_b, nabla_w)\n",
"\n",
" def evaluate(self, test_data):\n",
" \"\"\"Return the number of test inputs for which the neural\n",
" network outputs the correct result. Note that the neural\n",
" network's output is assumed to be the index of whichever\n",
" neuron in the final layer has the highest activation.\"\"\"\n",
" test_results = [(np.argmax(self.feedforward(x)), y)\n",
" for (x, y) in test_data]\n",
" return sum(int(x == y) for (x, y) in test_results)\n",
"\n",
" def cost_derivative(self, output_activations, y):\n",
" \"\"\"Return the vector of partial derivatives \\partial C_x /\n",
" \\partial a for the output activations.\"\"\"\n",
" return (output_activations-y)\n",
" \n",
" \n",
" \n",
"#Functions\n",
"def sigmoid(z):\n",
" return 1.0/(1.0+np.exp(-z))\n",
"\n",
"def sigmoid_prime(z):\n",
" return sigmoid(z)*(1-sigmoid(z))\n",
"\n",
"network=Network()"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"ename": "AttributeError",
"evalue": "'Network' object has no attribute 'Network'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-35-768076401f8b>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 86\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 87\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 88\u001b[0;31m \u001b[0mnet\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnetwork\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mNetwork\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m784\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m30\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m30\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 89\u001b[0m \u001b[0mnet\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mSGD\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtraining_data\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m30\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mtest_data\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtest_data\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mAttributeError\u001b[0m: 'Network' object has no attribute 'Network'"
]
}
],
"source": [
"# %load neural-networks-and-deep-learning/src/mnist_loader.py\n",
"\"\"\"\n",
"mnist_loader\n",
"~~~~~~~~~~~~\n",
"\n",
"A library to load the MNIST image data. For details of the data\n",
"structures that are returned, see the doc strings for ``load_data``\n",
"and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the\n",
"function usually called by our neural network code.\n",
"\"\"\"\n",
"\n",
"#### Libraries\n",
"# Standard library\n",
"import pickle\n",
"import gzip\n",
"\n",
"# Third-party libraries\n",
"import numpy as np\n",
"\n",
"def load_data():\n",
" \"\"\"Return the MNIST data as a tuple containing the training data,\n",
" the validation data, and the test data.\n",
"\n",
" The ``training_data`` is returned as a tuple with two entries.\n",
" The first entry contains the actual training images. This is a\n",
" numpy ndarray with 50,000 entries. Each entry is, in turn, a\n",
" numpy ndarray with 784 values, representing the 28 * 28 = 784\n",
" pixels in a single MNIST image.\n",
"\n",
" The second entry in the ``training_data`` tuple is a numpy ndarray\n",
" containing 50,000 entries. Those entries are just the digit\n",
" values (0...9) for the corresponding images contained in the first\n",
" entry of the tuple.\n",
"\n",
" The ``validation_data`` and ``test_data`` are similar, except\n",
" each contains only 10,000 images.\n",
"\n",
" This is a nice data format, but for use in neural networks it's\n",
" helpful to modify the format of the ``training_data`` a little.\n",
" That's done in the wrapper function ``load_data_wrapper()``, see\n",
" below.\n",
" \"\"\"\n",
" f = gzip.open('../data/mnist.pkl.gz', 'rb')\n",
" training_data, validation_data, test_data = cPickle.load(f)\n",
" f.close()\n",
" return (training_data, validation_data, test_data)\n",
"\n",
"def load_data_wrapper():\n",
" \"\"\"Return a tuple containing ``(training_data, validation_data,\n",
" test_data)``. Based on ``load_data``, but the format is more\n",
" convenient for use in our implementation of neural networks.\n",
"\n",
" In particular, ``training_data`` is a list containing 50,000\n",
" 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray\n",
" containing the input image. ``y`` is a 10-dimensional\n",
" numpy.ndarray representing the unit vector corresponding to the\n",
" correct digit for ``x``.\n",
"\n",
" ``validation_data`` and ``test_data`` are lists containing 10,000\n",
" 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional\n",
" numpy.ndarry containing the input image, and ``y`` is the\n",
" corresponding classification, i.e., the digit values (integers)\n",
" corresponding to ``x``.\n",
"\n",
" Obviously, this means we're using slightly different formats for\n",
" the training data and the validation / test data. These formats\n",
" turn out to be the most convenient for use in our neural network\n",
" code.\"\"\"\n",
" tr_d, va_d, te_d = load_data()\n",
" training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]\n",
" training_results = [vectorized_result(y) for y in tr_d[1]]\n",
" training_data = zip(training_inputs, training_results)\n",
" validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]\n",
" validation_data = zip(validation_inputs, va_d[1])\n",
" test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]\n",
" test_data = zip(test_inputs, te_d[1])\n",
" return (training_data, validation_data, test_data)\n",
"\n",
"def vectorized_result(j):\n",
" \"\"\"Return a 10-dimensional unit vector with a 1.0 in the jth\n",
" position and zeroes elsewhere. This is used to convert a digit\n",
" (0...9) into a corresponding desired output from the neural\n",
" network.\"\"\"\n",
" e = np.zeros((10, 1))\n",
" e[j] = 1.0\n",
" return e\n",
"\n",
"net=network.Network([784,30,30])\n",
"net.SGD(training_data,30,10,3,test_data=test_data)"
]
},
{
"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 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,109 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import mglearn\n",
"import numpy as np\n",
"import pandas as pd\n",
"import os\n",
"from scipy import signal\n",
"from sklearn.datasets import load_boston\n",
"from sklearn.preprocessing import MinMaxScaler, PolynomialFeatures\n",
"from mglearn.make_blobs import make_blobs\n",
"\n",
"#DATA_PATH = os.path.join(os.path.dirname(__file__), \"data\")\n",
"\n",
"\n",
"def make_forge():\n",
" # a carefully hand-designed dataset lol\n",
" X, y = make_blobs(centers=2, random_state=4, n_samples=30)\n",
" y[np.array([7, 27])] = 0\n",
" mask = np.ones(len(X), dtype=np.bool)\n",
" mask[np.array([0, 1, 5, 26])] = 0\n",
" X, y = X[mask], y[mask]\n",
" return X, y\n",
"\n",
"\n",
"def make_wave(n_samples=100):\n",
" rnd = np.random.RandomState(42)\n",
" x = rnd.uniform(-3, 3, size=n_samples)\n",
" y_no_noise = (np.sin(4 * x) + x)\n",
" y = (y_no_noise + rnd.normal(size=len(x))) / 2\n",
" return x.reshape(-1, 1), y\n",
"\n",
"\n",
"def load_extended_boston():\n",
" boston = load_boston()\n",
" X = boston.data\n",
"\n",
" X = MinMaxScaler().fit_transform(boston.data)\n",
" X = PolynomialFeatures(degree=2, include_bias=False).fit_transform(X)\n",
" return X, boston.target\n",
"\n",
"\n",
"def load_citibike():\n",
" data_mine = pd.read_csv(os.path.join(DATA_PATH, \"citibike.csv\"))\n",
" data_mine['one'] = 1\n",
" data_mine['starttime'] = pd.to_datetime(data_mine.starttime)\n",
" data_starttime = data_mine.set_index(\"starttime\")\n",
" data_resampled = data_starttime.resample(\"3h\").sum().fillna(0)\n",
" return data_resampled.one\n",
"\n",
"\n",
"def make_signals():\n",
" # fix a random state seed\n",
" rng = np.random.RandomState(42)\n",
" n_samples = 2000\n",
" time = np.linspace(0, 8, n_samples)\n",
" # create three signals\n",
" s1 = np.sin(2 * time) # Signal 1 : sinusoidal signal\n",
" s2 = np.sign(np.sin(3 * time)) # Signal 2 : square signal\n",
" s3 = signal.sawtooth(2 * np.pi * time) # Signal 3: saw tooth signal\n",
"\n",
" # concatenate the signals, add noise\n",
" S = np.c_[s1, s2, s3]\n",
" S += 0.2 * rng.normal(size=S.shape)\n",
"\n",
" S /= S.std(axis=0) # Standardize data\n",
" S -= S.min()\n",
" return S\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,153 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"from scipy import optimize\n",
"\n",
"class Neural_Network(object):\n",
" def __init__(self, Lambda=0): \n",
" #Define Hyperparameters\n",
" self.inputLayerSize = 2\n",
" self.outputLayerSize = 1\n",
" self.hiddenLayerSize = 3\n",
" \n",
" #Weights (parameters)\n",
" self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize)\n",
" self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize)\n",
" \n",
" #Regularization Parameter:\n",
" self.Lambda = Lambda\n",
" \n",
" def forward(self, X):\n",
" #Propogate inputs though network\n",
" self.z2 = np.dot(X, self.W1)\n",
" self.a2 = self.sigmoid(self.z2)\n",
" self.z3 = np.dot(self.a2, self.W2)\n",
" yHat = self.sigmoid(self.z3) \n",
" return yHat\n",
" \n",
" def sigmoid(self, z):\n",
" #Apply sigmoid activation function to scalar, vector, or matrix\n",
" return 1/(1+np.exp(-z))\n",
" \n",
" def sigmoidPrime(self,z):\n",
" #Gradient of sigmoid\n",
" return np.exp(-z)/((1+np.exp(-z))**2)\n",
" \n",
" def costFunction(self, X, y):\n",
" #Compute cost for given X,y, use weights already stored in class.\n",
" self.yHat = self.forward(X)\n",
" J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.Lambda/2)*(np.sum(self.W1**2)+np.sum(self.W2**2))\n",
" return J\n",
" \n",
" def costFunctionPrime(self, X, y):\n",
" #Compute derivative with respect to W and W2 for a given X and y:\n",
" self.yHat = self.forward(X)\n",
" \n",
" delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))\n",
" #Add gradient of regularization term:\n",
" dJdW2 = np.dot(self.a2.T, delta3)/X.shape[0] + self.Lambda*self.W2\n",
" \n",
" delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)\n",
" #Add gradient of regularization term:\n",
" dJdW1 = np.dot(X.T, delta2)/X.shape[0] + self.Lambda*self.W1\n",
" \n",
" return dJdW1, dJdW2\n",
" \n",
" #Helper functions for interacting with other methods/classes\n",
" def getParams(self):\n",
" #Get W1 and W2 Rolled into vector:\n",
" params = np.concatenate((self.W1.ravel(), self.W2.ravel()))\n",
" return params\n",
" \n",
" def setParams(self, params):\n",
" #Set W1 and W2 using single parameter vector:\n",
" W1_start = 0\n",
" W1_end = self.hiddenLayerSize*self.inputLayerSize\n",
" self.W1 = np.reshape(params[W1_start:W1_end], \\\n",
" (self.inputLayerSize, self.hiddenLayerSize))\n",
" W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize\n",
" self.W2 = np.reshape(params[W1_end:W2_end], \\\n",
" (self.hiddenLayerSize, self.outputLayerSize))\n",
" \n",
" def computeGradients(self, X, y):\n",
" dJdW1, dJdW2 = self.costFunctionPrime(X, y)\n",
" return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))\n",
" \n",
" \n",
"class trainer(object):\n",
" def __init__(self, N):\n",
" #Make Local reference to network:\n",
" self.N = N\n",
" \n",
" def callbackF(self, params):\n",
" self.N.setParams(params)\n",
" self.J.append(self.N.costFunction(self.X, self.y))\n",
" self.testJ.append(self.N.costFunction(self.testX, self.testY))\n",
" \n",
" def costFunctionWrapper(self, params, X, y):\n",
" self.N.setParams(params)\n",
" cost = self.N.costFunction(X, y)\n",
" grad = self.N.computeGradients(X,y)\n",
" return cost, grad\n",
" \n",
" def train(self, trainX, trainY, testX, testY):\n",
" #Make an internal variable for the callback function:\n",
" self.X = trainX\n",
" self.y = trainY\n",
" \n",
" self.testX = testX\n",
" self.testY = testY\n",
"\n",
" #Make empty list to store training costs:\n",
" self.J = []\n",
" self.testJ = []\n",
" \n",
" params0 = self.N.getParams()\n",
"\n",
" options = {'maxiter': 200, 'disp' : True}\n",
" _res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \\\n",
" args=(trainX, trainY), options=options, callback=self.callbackF)\n",
"\n",
" self.N.setParams(_res.x)\n",
" self.optimizationResults = _res\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,173 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "train() missing 1 required positional argument: 'testY'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-5-e816aa3fc208>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m 114\u001b[0m \u001b[0mtrainX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtestX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrainY\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtestY\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtrain_test_split\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0miris\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'data'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0miris\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'target'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrandom_state\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 115\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 116\u001b[0;31m \u001b[0miris_train\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtrainer\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtrain\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mtrainX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrainY\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtestX\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtestY\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: train() missing 1 required positional argument: 'testY'"
]
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"from sklearn.datasets import load_iris\n",
"iris=load_iris()\n",
"\n",
"from scipy import optimize\n",
"\n",
"class Neural_Network(object):\n",
" def __init__(self, Lambda=0): \n",
" #Define Hyperparameters\n",
" self.inputLayerSize = 2\n",
" self.outputLayerSize = 1\n",
" self.hiddenLayerSize = 3\n",
" \n",
" #Weights (parameters)\n",
" self.W1 = np.random.randn(self.inputLayerSize,self.hiddenLayerSize)\n",
" self.W2 = np.random.randn(self.hiddenLayerSize,self.outputLayerSize)\n",
" \n",
" #Regularization Parameter:\n",
" self.Lambda = Lambda\n",
" \n",
" def forward(self, X):\n",
" #Propogate inputs though network\n",
" self.z2 = np.dot(X, self.W1)\n",
" self.a2 = self.sigmoid(self.z2)\n",
" self.z3 = np.dot(self.a2, self.W2)\n",
" yHat = self.sigmoid(self.z3) \n",
" return yHat\n",
" \n",
" def sigmoid(self, z):\n",
" #Apply sigmoid activation function to scalar, vector, or matrix\n",
" return 1/(1+np.exp(-z))\n",
" \n",
" def sigmoidPrime(self,z):\n",
" #Gradient of sigmoid\n",
" return np.exp(-z)/((1+np.exp(-z))**2)\n",
" \n",
" def costFunction(self, X, y):\n",
" #Compute cost for given X,y, use weights already stored in class.\n",
" self.yHat = self.forward(X)\n",
" J = 0.5*sum((y-self.yHat)**2)/X.shape[0] + (self.Lambda/2)*(np.sum(self.W1**2)+np.sum(self.W2**2))\n",
" return J\n",
" \n",
" def costFunctionPrime(self, X, y):\n",
" #Compute derivative with respect to W and W2 for a given X and y:\n",
" self.yHat = self.forward(X)\n",
" \n",
" delta3 = np.multiply(-(y-self.yHat), self.sigmoidPrime(self.z3))\n",
" #Add gradient of regularization term:\n",
" dJdW2 = np.dot(self.a2.T, delta3)/X.shape[0] + self.Lambda*self.W2\n",
" \n",
" delta2 = np.dot(delta3, self.W2.T)*self.sigmoidPrime(self.z2)\n",
" #Add gradient of regularization term:\n",
" dJdW1 = np.dot(X.T, delta2)/X.shape[0] + self.Lambda*self.W1\n",
" \n",
" return dJdW1, dJdW2\n",
" \n",
" #Helper functions for interacting with other methods/classes\n",
" def getParams(self):\n",
" #Get W1 and W2 Rolled into vector:\n",
" params = np.concatenate((self.W1.ravel(), self.W2.ravel()))\n",
" return params\n",
" \n",
" def setParams(self, params):\n",
" #Set W1 and W2 using single parameter vector:\n",
" W1_start = 0\n",
" W1_end = self.hiddenLayerSize*self.inputLayerSize\n",
" self.W1 = np.reshape(params[W1_start:W1_end], \\\n",
" (self.inputLayerSize, self.hiddenLayerSize))\n",
" W2_end = W1_end + self.hiddenLayerSize*self.outputLayerSize\n",
" self.W2 = np.reshape(params[W1_end:W2_end], \\\n",
" (self.hiddenLayerSize, self.outputLayerSize))\n",
" \n",
" def computeGradients(self, X, y):\n",
" dJdW1, dJdW2 = self.costFunctionPrime(X, y)\n",
" return np.concatenate((dJdW1.ravel(), dJdW2.ravel()))\n",
" \n",
" \n",
"class trainer(object):\n",
" def __init__(self, N):\n",
" #Make Local reference to network:\n",
" self.N = N\n",
" \n",
" def callbackF(self, params):\n",
" self.N.setParams(params)\n",
" self.J.append(self.N.costFunction(self.X, self.y))\n",
" self.testJ.append(self.N.costFunction(self.testX, self.testY))\n",
" \n",
" def costFunctionWrapper(self, params, X, y):\n",
" self.N.setParams(params)\n",
" cost = self.N.costFunction(X, y)\n",
" grad = self.N.computeGradients(X,y)\n",
" return cost, grad\n",
" \n",
" def train(self, trainX, trainY, testX, testY):\n",
" #Make an internal variable for the callback function:\n",
" self.X = trainX\n",
" self.y = trainY\n",
" \n",
" self.testX = testX\n",
" self.testY = testY\n",
"\n",
" #Make empty list to store training costs:\n",
" self.J = []\n",
" self.testJ = []\n",
" \n",
" params0 = self.N.getParams()\n",
"\n",
" options = {'maxiter': 200, 'disp' : True}\n",
" _res = optimize.minimize(self.costFunctionWrapper, params0, jac=True, method='BFGS', \\\n",
" args=(trainX, trainY), options=options, callback=self.callbackF)\n",
"\n",
" self.N.setParams(_res.x)\n",
" self.optimizationResults = _res\n",
"\n",
"from sklearn.model_selection import train_test_split\n",
"trainX, testX, trainY, testY=train_test_split(iris['data'], iris['target'], random_state=0)\n",
"\n",
"iris_train=trainer.train(trainX, trainY, testX, testY)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,66 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[ 126.84247142 125.01176842]\n"
]
}
],
"source": [
"from sklearn.preprocessing import PolynomialFeatures\n",
"from sklearn import linear_model\n",
"import matplotlib.pyplot as plt \n",
"\n",
"X = [[0.44, 0.68], [0.99, 0.23]]\n",
"vector = [109.85, 155.72]\n",
"predict= [[0.49, 0.18], [0.47, 0.22]]\n",
"\n",
"poly = PolynomialFeatures(degree=2)\n",
"X_ = poly.fit_transform(X)\n",
"predict_ = poly.fit_transform(predict)\n",
"\n",
"clf = linear_model.LinearRegression()\n",
"clf.fit(X_, vector)\n",
"y=clf.predict(predict_)\n",
"print (clf.predict(predict_))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,84 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Output after training: [[ 6.55109972e-03 9.93684857e-01 9.93925710e-01 6.62304973e-03]\n",
" [ 1.71082162e-03 9.97516440e-01 9.97766376e-01 1.82685927e-03]\n",
" [ 2.05800960e-03 9.98268211e-01 9.97548919e-01 1.77362990e-03]\n",
" [ 5.35659849e-04 9.99320839e-01 9.99100767e-01 4.87503198e-04]]\n"
]
}
],
"source": [
"import numpy as np\n",
"\n",
"#sigmoid\n",
"def nonlin(x, deriv=False):\n",
" if (deriv==True):\n",
" return x*(1-x)\n",
" return 1/(1+np.exp(-x))\n",
"\n",
"#input data\n",
"x=np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])\n",
"\n",
"#output data\n",
"y=np.array([0,1,1,0]).T\n",
"\n",
"#seed random numbers to make calculation\n",
"np.random.seed(1)\n",
"\n",
"#initialize weights with mean=0\n",
"syn0=2*np.random.random((3,4))-1\n",
"\n",
"for iter in range(10000):\n",
" #forward propogation\n",
" l0=x\n",
" l1=nonlin(np.dot(l0,syn0))\n",
" l1_error=y-l1\n",
" #multiply error by slope of sigmoid at values of l1\n",
" l1_delta=l1_error*nonlin(l1,True)\n",
" #update weights\n",
" syn0+=np.dot(l0.T, l1_delta)\n",
" \n",
"print(\"Output after training: \",l1 )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,157 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\n",
"Extracting /tmp/data/train-images-idx3-ubyte.gz\n",
"Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\n",
"Extracting /tmp/data/train-labels-idx1-ubyte.gz\n",
"Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\n",
"Extracting /tmp/data/t10k-images-idx3-ubyte.gz\n",
"Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\n",
"Extracting /tmp/data/t10k-labels-idx1-ubyte.gz\n",
"WARNING:tensorflow:From <ipython-input-1-92265976c34d>:45: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
"Instructions for updating:\n",
"\n",
"Future major versions of TensorFlow will allow gradients to flow\n",
"into the labels input on backprop by default.\n",
"\n",
"See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
"\n",
"WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/python/util/tf_should_use.py:118: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.\n",
"Instructions for updating:\n",
"Use `tf.global_variables_initializer` instead.\n",
"Epoch 0 completed out of 10 loss: 1664569.60834\n",
"Epoch 1 completed out of 10 loss: 414550.968437\n",
"Epoch 2 completed out of 10 loss: 229022.354944\n",
"Epoch 3 completed out of 10 loss: 136420.393392\n",
"Epoch 4 completed out of 10 loss: 88019.3560204\n",
"Epoch 5 completed out of 10 loss: 56024.820509\n",
"Epoch 6 completed out of 10 loss: 37434.4423951\n",
"Epoch 7 completed out of 10 loss: 29640.3100017\n",
"Epoch 8 completed out of 10 loss: 24399.9572706\n",
"Epoch 9 completed out of 10 loss: 23351.0056713\n",
"Accuracy: 0.9534\n"
]
}
],
"source": [
"import tensorflow as tf\n",
"from tensorflow.examples.tutorials.mnist import input_data\n",
"mnist=input_data.read_data_sets(\"/tmp/data/\", one_hot=True) #one component is on, all others are off\n",
"#10 classes, 0 through 9\n",
"#one-hot outputs 0=[1,0,0,0,0,0,0,0,0], being the 1 is in the algorithm's guess (0)\n",
"#3=[0,0,0,1,0,0,0,0,0]\n",
"n_nodes_hl1=500 #hl1 = hidden layer 1\n",
"n_nodes_hl2=500\n",
"n_nodes_hl3=500\n",
"n_classes=10 #number of categories\n",
"batch_size=100 #divies up the data to be more efficient, as opposed to loading all samples at once\n",
"\n",
"x=tf.placeholder('float',[None, 784])\n",
"y=tf.placeholder('float')\n",
"\n",
"def neural_network_model(data):\n",
" #(inputs*weights)+biases\n",
" hidden_1_layer={'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])), \n",
" 'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}\n",
" \n",
" hidden_2_layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])), \n",
" 'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}\n",
" \n",
" hidden_3_layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])), \n",
" 'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}\n",
" \n",
" output_layer={'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),\n",
" 'biases': tf.Variable(tf.random_normal([n_classes]))}\n",
" \n",
" l1=tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])\n",
" l1=tf.nn.relu(l1)\n",
" \n",
" l2=tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])\n",
" l2=tf.nn.relu(l2)\n",
" \n",
" l3=tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])\n",
" l3=tf.nn.relu(l3)\n",
" \n",
" output=tf.matmul(l3, output_layer['weights'])+ output_layer['biases']\n",
" \n",
" return output\n",
" \n",
"def train_neural_network(x):\n",
" prediction=neural_network_model(x)\n",
" cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y))\n",
" optimizer=tf.train.AdamOptimizer().minimize(cost)\n",
" \n",
" hm_epochs=10\n",
" \n",
" with tf.Session() as sess:\n",
" sess.run(tf.initialize_all_variables())\n",
" \n",
" for epoch in range(hm_epochs):\n",
" epoch_loss=0\n",
" for _ in range(int(mnist.train.num_examples/batch_size)):\n",
" epoch_x,epoch_y=mnist.train.next_batch(batch_size)\n",
" _,c=sess.run([optimizer,cost], feed_dict={x:epoch_x, y:epoch_y})\n",
" epoch_loss+=c\n",
" print('Epoch', epoch, 'completed out of ', hm_epochs, 'loss:', epoch_loss)\n",
" \n",
" correct=tf.equal(tf.argmax(prediction,1), tf.argmax(y,1))\n",
" \n",
" accuracy=tf.reduce_mean(tf.cast(correct, 'float'))\n",
" print('Accuracy:', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))\n",
" \n",
"\n",
" \n",
" \n",
"train_neural_network(x)"
]
},
{
"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 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,101 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[ 0. 0. 5. ..., 0. 0. 0.]\n",
" [ 0. 0. 0. ..., 10. 0. 0.]\n",
" [ 0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WCLpakkv2t7W+9wPIuKRFmdCf9dJWt87\n2OyWtLrleQbS+p/JANSnC6foAGpC4EBiBA4kRuBAYgQOJEbgQGIEDiRG4EBi/wYWKZOShpwGCQAA\nAABJRU5ErkJggg==\n",
"text/plain": [
"<matplotlib.figure.Figure at 0x1a17854da0>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"import matplotlib.pyplot as plt\n",
"import numpy\n",
"from sklearn import datasets\n",
"from sklearn import svm\n",
"digits=datasets.load_digits()\n",
"\n",
"clf=svm.SVC(gamma=0.001, C=100)\n",
"print(digits.data)\n",
"x,y=digits.data[:-1], digits.target[:-1]\n",
"clf.fit(x,y)\n",
"\n",
"print (digits.data)\n",
"print (x.shape)\n",
"\n",
"print(\"prediction:\", clf.predict(digits.data))\n",
"plt.imshow(digits.images[-2])\n",
"plt.show()\n"
]
},
{
"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 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,117 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" Bounce_Rate Visitors\n",
"Day \n",
"1 65 43\n",
"2 72 53\n",
"3 62 34\n",
"4 64 45\n",
"5 54 64\n",
"6 66 34\n",
"Day\n",
"1 43\n",
"2 53\n",
"3 34\n",
"4 45\n",
"5 64\n",
"6 34\n",
"Name: Visitors, dtype: int64\n",
" Bounce_Rate Visitors\n",
"Day \n",
"1 65 43\n",
"2 72 53\n",
"3 62 34\n",
"4 64 45\n",
"5 54 64\n",
"6 66 34\n",
"[43, 53, 34, 45, 64, 34]\n",
"[[65 43]\n",
" [72 53]\n",
" [62 34]\n",
" [64 45]\n",
" [54 64]\n",
" [66 34]]\n"
]
}
],
"source": [
"import pandas as pd\n",
"import matplotlib.pyplot as plt\n",
"from matplotlib import style\n",
"style.use('ggplot')\n",
"import numpy as np\n",
"\n",
"web_stats={'Day':[1,2,3,4,5,6],\n",
" 'Visitors':[43,53,34,45,64,34],\n",
" 'Bounce_Rate':[65,72,62,64,54,66]}\n",
"\n",
"df=pd.DataFrame(web_stats)\n",
"\n",
"#print(df) #df stands for data frame\n",
"#print(df.head()) #prints the first 5 rows\n",
"#print(df.tail()) #prints the last 5 rows\n",
"#Specifying the number in the parentheses gives that number of rows\n",
"#print(df.head(2))\n",
"#print(df.tail(2))\n",
"\n",
"#df=df.set_index('Day')\n",
"\n",
"#OR you can do this:\n",
"df.set_index('Day', inplace=True)\n",
"print(df)\n",
"\n",
"#print (df['Visitors']) #prints specific column OR\n",
"print (df.Visitors)\n",
"\n",
"#referencing multiple columns\n",
"print (df[['Bounce_Rate','Visitors']])\n",
"\n",
"#making a list out of a column; this only work with one column because more than one would\n",
"#treat the dictionary like an array, which it isn't\n",
"print (df.Visitors.tolist())\n",
"\n",
"#to make it an array\n",
"print (np.array(df[['Bounce_Rate','Visitors']]))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,106 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Tensor(\"Mul_11:0\", shape=(4,), dtype=int32)\n",
"[ 5 12 21 32]\n",
"[ 5 12 21 32]\n",
"30\n",
"30\n",
"30\n",
"30\n"
]
}
],
"source": [
"# Import `tensorflow`\n",
"import tensorflow as tf\n",
"import os\n",
"\n",
"# Initialize two constants\n",
"x1 = tf.constant([1,2,3,4])\n",
"x2 = tf.constant([5,6,7,8])\n",
"\n",
"# Multiply\n",
"result = tf.multiply(x1, x2)\n",
"\n",
"# Print the result\n",
"print(result)\n",
"\n",
"# Intialize the Session\n",
"sess = tf.Session()\n",
"\n",
"# Print the result\n",
"print(sess.run(result))\n",
"\n",
"# Close the session\n",
"sess.close()\n",
"\n",
"#Or you can run the session like so:\n",
"with tf.Session() as sess:\n",
" output = sess.run(result)\n",
" print(output)\n",
"\n",
" \n",
"y1=tf.constant(5)\n",
"y2=tf.constant(6)\n",
"result=tf.multiply(y1, y2)\n",
"sess=tf.Session()\n",
"print(sess.run(result))\n",
"sess.close()\n",
"\n",
"#or\n",
"\n",
"with tf.Session() as sess:\n",
" print (sess.run(result))\n",
" \n",
"#this closes the session automatically\n",
"\n",
"#try this:\n",
"with tf.Session() as sess:\n",
" output=sess.run(result)\n",
" print (output)\n",
" \n",
"print (output)\n",
"#you can't run sess.run(result) outside of the with action"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,112 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"import nltk\n",
"from nltk.tokenize import word_tokenize\n",
"from nltk.stem import WordNetLemmatizer\n",
"import numpy as np\n",
"import random\n",
"import pickle\n",
"from collections import Counter\n",
"\n",
"lemmatizer=WordNetLemmatizer()\n",
"hm_lines=1000000\n",
"\n",
"def create_lexicon(pos,neg):\n",
" lexicon=[]\n",
" for fi in [pos,neg]:\n",
" with open(fi, 'ri') as f:\n",
" contents=f.readlines()\n",
" for l in contents[:hm_lines]:\n",
" all_words=word_tokenize(l.lower())\n",
" lexicon+=list(all_words)\n",
" \n",
" \n",
" lexicon=[lemmatizer.lemmatize(i) for i in lexicon] \n",
" w_counts=Counter(lexicon)\n",
" l2=[]\n",
" for w in w_counts:\n",
" if 1000 > w_counts[w] >50:\n",
" l2.append(w)\n",
" \n",
" return l2\n",
" \n",
" \n",
"def sample_handling(sample, lexicon, classification):\n",
" featureset=[]\n",
" with open(sample, 'ri') as f:\n",
" contents=f.readlines()\n",
" for l in contents[:hm_lines]:\n",
" current_words=word_tokenize(l.lower())\n",
" current_words=[lemmatizer.lemmatize(i) for i in current_words]\n",
" features=np.zeros(len(lexicon))\n",
" for word in current_words:\n",
" if word.lower() in lexicon:\n",
" index_value=lexicon.index(word.lower())\n",
" feature[index_value]+=1\n",
" features=list(features)\n",
" featureset.append([features, classification])\n",
" \n",
" return featureset\n",
" \n",
" \n",
" \n",
" \n",
"def creat_featuresets_and_labels(pos, neg, test_size=0.1):\n",
" lexicon=create_lexicon(pos,neg)\n",
" features=[]\n",
" features+=sample_handling('pos.txt', lexicon, [1,0])\n",
" features+=sample_handling('neg.txt', lexicon, [0,1])\n",
" random.shuffle(features)\n",
" features=np.array(features)\n",
" testing_size=int(test_size*len(features))\n",
" train_x=list(features[:,0][:-testing_size]) #creates a list of the 0th element of every list in the overall list\n",
" train_y=list(features[:,1][:-testing_size])\n",
" \n",
" test_x=list(features[:,0][-testing_size:]) \n",
" test_y=list(features[:,1][-testing_size:])\n",
" \n",
" return train_x, train_y, test_x, test_y\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}