markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
*Note*: the brackets are optional
t = 1, 2, 3, 4 t
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
"Unpacking": as with lists (or any iterable), it is possible to extract values in a tuple and assign them to new variables
t[1:3] second_item, third_item = t[1], t[2] print(second_item) print(third_item)
2 3
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
**Tip**: unpack undefined number of items
second_item, *greater_items = t[1:] second_item greater_items
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
DictionnariesMap keys to values
d = {'key1': 0, 'key2': 1} d
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Keys must be unique.But be careful: no error is raised if you provide multiple, identical keys!
d = {'key1': 0, 'key2': 1, 'key1': 3} d
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Indexing dictionnaries by key
d['key1']
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Keys are not limited to strings, they can be many things (but not anything, we'll see later)
d = {'key1': 0, 2: 1, 3.: 3} d[2]
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Get keys or values
d.keys() d.values() a[d['key1']] d = { 'benoit': { 'age': 33, 'section':'5.5' } } d['benoit']['age']
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Mutable vs. immutable We can change the value of a variable in place (after we create the variable) or we can't. For example, lists are mutable.
a = [1, 2, 3, 4] a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Change the value of one item in place
a[0] = 'one' a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Append one item at the end of the list
a.append(5) a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Insert one item at a given position
a.insert(0, 'zero') a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Extract and remove the last item
a.pop() a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Dictionnaries are mutable (note the order of the keys in the printed dict)
d = {'key1': 0, 'key2': 1, 'key3': 2} d['key4'] = 4 d
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Pop an item of given key
d.pop('key1') d
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Tuples are immutable!
t = (1, 2, 3, 4) t.append(5)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Strings are immutable!
food = "bradwurst" food[0:4] = "cury"
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
But is easy and efficient to create new strings
food = "curry" + food[-5:] food
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
A reason why strings are immutable?The keys of a dictionnary cannot be mutable, e.g., we cannot not use a list
d = {[1, 3]: 0}
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
The keys of a dictionnary cannot be mutable, for a quite obvious reason that it is used as indexes, like in a database. If we allow changing the indexes, it can be a real mess!If strings were mutable, then we could'nt use it as keys in dictionnaries.*Note*: more precisely, keys of a dictionnary must be "hashable". Var...
a = [1, 2, 3] b = a b[0] = 'one' a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Explanation: the concept of variable is different in Python than in, e.g., C or Fortran`a = [1, 2, 3]` means we create a list object and we bind this object to a name (label or identifier) "a"`b = a` means we bind the same object to a new name "b"You can find more details and good illustrations here: https://nedbatchel...
id(a) id(b)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
`is` : check whether two identifiers are bound to the same value (object)
a is b
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
OK, but how do you explain this?
a = 1 b = a b = 2 a a is b id(a) id(b)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Can you explain what's going on here?
a = 1 b = 2 b = a + b b
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Where does go the value "2" that was initially bounded to "b"? OK, now what about this? Very confusing!
a = 1 b = 1 a is b a = 1. b = 1. a is b
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Dynamic, strong, duck typing Dynamic typing: no need to explicitly declare a type of an object/variable before using it. This is done automatically depending on the given object/value.
a = 1 type(a)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Strong typing: Converting from one type to another must be explicit, i.e., a value of a given type cannot be magically converted into another type
a + '1' a + int('1') eval('1 + 2 * 3')
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
An exception: integer to float casting
a + 1.
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Duck typing: The type of an object doesn't really matter. What an object can or cannot do is more important.> "If it walks like a duck and it quacks like a duck, then it must be a duck" For example, we can show that iterating trough list, string or dict can be done using the exact same loop
var = [1, 2, 3, 4] for i in var: print(i) var = 'abcd' for i in var: print(i) var = {'key1': 1, 'key2': 2} for i in var: print(i)
key1 key2
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
In the last case, iterating a dictionnary uses the keys.It is possible to iterate the values:
for v in var.values(): print(v)
1 2
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Or more useful, iterate trough both keys and values
for k, v in var.items(): print(k, v) t = ('key1', 1) k, v = t var.items()
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Arithmetic operators can be obviously applied on integer, float...
1 + 1 1 + 2.
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
...but also on strings and lists (in this case it does concatenation)
[1, 2, 3] + ['a', 'b', 'c'] 'other' + 'one'
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
... and also mixing the types, e.g., repeat sequence x times
[1, 2, 3] * 3 'one' * 3
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
...although, everything is not possible
[1, 2, 3] * 3.5
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Boolean: what is True and what is False
print(True) print(False) print(bool(0)) print(bool(-1)) a = 1.7 if a: print('non zero') print(bool('')) print(bool('no empty')) print(bool([])) print(bool([1, 2])) print(bool({})) print(bool({'key1': 1})) d = {} if not d: print('there is no item')
there is no item
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
list comprehension Example: we create a list from another one using a `for` loop
ints = [1, 3, 5, 0, 2, 0] true_or_false = [] for i in ints: true_or_false.append(bool(i)) true_or_false
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
But there is a much more succint way to do it. It is still (and maybe even more) readable
true_or_false = [bool(i) for i in ints] true_or_false
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
More complex example, with conditions
float_no3 = [float(i) for i in ints if i != 3] float_no3
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Other kinds of conditions(It starts to be less readable -> don't abuse list comprehension)
float_str3 = [float(i) if i != 3 else str(i) for i in ints] float_str3
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Dict comprehensions
int2float_map = {i: float(i) for i in ints} int2float_map
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
FunctionsA function take value(s) as input and (optionally) return value(s) as outputinputs = arguments
def add(a, b): """Add two things.""" return a + b def print_the_argument(arg): print(arg) print_the_argument('a string')
a string
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
We can call it several times with different values
add(1, 3) help(add)
Help on function add in module __main__: add(a, b) Add two things.
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Nested calls
add(add(1, 2), 3)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Duck typing is really useful! A single function for doing many things (write less code)
add(1., 2.) add('one', 'two') add([1, 2, 3], [1, 2, 3])
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Functions have a scope that is local
a = 1 def func(): a = 2 a func() a
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Call by value?
def func(j): j = j + 1 print('inside: ', j) return j i = 1 print('before:', i) i = func(i) print('after:', i)
before: 1 inside: 2 after: 2
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Not really...
def func(li): li[0] = 1000 print('inside: ', li[0]) li = [1] print('before:', li[0]) func(li) print('after:', li[0])
before: 1 inside: 1000 after: 1000
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Composing functions (start to look like functional programming)
C2K_OFFSET = 273.15 def fahr_to_kelvin(temp): """convert temp from fahrenheit to kelvin""" return ((temp - 32) * (5/9)) + C2K_OFFSET def kelvin_to_celsius(temp_k): # convert temperature from kevin to celsius return temp_k - C2K_OFFSET def fahr_to_celsius(temp_f): temp_k = fahr_to_kelvin(temp_f) ...
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Function docstring (help) Default argument values (keyword arguments)
def display(a=1, b=2, c=3): print(a, b, c) display(b=4)
1 4 3
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
When calling a function, the order of the keyword arguments doesn't matterBut the order matters for positional arguments!!
display(c=5, a=1) display(3)
3 2 3
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Mix positional and keyword arguments: positional arguments must be added before keyword arguments
def display(c, a=1, b=2): print(a, b, c) display(1000)
1 2 1000
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
What's going on here?
def add_to_list(li=[], value=1): li.append(value) return li add_to_list() add_to_list() add_to_list()
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Try running again the cell that defines the function, and then the cells that call the functionThis is sooo confusing! So you shouldn't use mutable objects as default valuesWorkaround:
def add_to_list(li=None, value=1): if li is None: li = [] li.append(value) return li add_to_list() add_to_list()
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Arbitrary number of arguments
def display_args(*args): print(args) nb_args = len(args) print(nb_args) print(*args) display_args('one') display_args(1, '2', 'bradwurst')
(1, '2', 'bradwurst') 3 1 2 bradwurst
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Arbitrary number of keyword arguments
def display_args_kwargs(*args, **kwargs): print(*args) print(kwargs) display_args_kwargs('one', 2, three=3.)
one 2 {'three': 3.0}
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Return more than one value (tuple)
def spherical_coords(x, y, z): # convert return r, theta, phi
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
ModulesModules are Python code in (`.py`) files that can be imported from within Python.Like functions, it allows to reusing the code in different contexts. Write a module with the temperature conversion functions above(note: the `%%writefile` is a magic cell command in the notebook that writes the content of the cel...
%%writefile temp_converter.py C2K_OFFSET = 273.15 def fahr_to_kelvin(temp): """convert temp from fahrenheit to kelvin""" return ((temp - 32) * (5/9)) + C2K_OFFSET def kelvin_to_celsius(temp_k): # convert temperature from kevin to celsius return temp_k - C2K_OFFSET def fahr_to_celsius(temp_f): te...
Overwriting temp_converter.py
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Import a module
import temp_converter
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Access the functions imported with the module using the module name as a "namespace"**Tip**: imported module + dot + for autocompletion
temp_converter.fahr_to_celsius(100.)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Import the module with a (short) alias for the namespace
import temp_converter as tc tc.fahr_to_celsius(100.)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Import just a function from the module
from temp_converter import fahr_to_celsius fahr_to_celsius(100.)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Import everything in the module (without using a namespace)Strongly discouraged!! Name conflicts!
from temp_converter import * kelvin_to_celsius(270)
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
(Text) file IOLet's create a small file with some data
%%writefile data.csv "depth", "some_variable" 200, 2.4e2 400, 5.6e2 600, 2.6e8
Writing data.csv
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Open the file using Python:
f = open("data.csv", "r") f
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Read the content
raw_data = f.readlines() raw_data
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
What happens here?
f.readlines() f.seek(0) f.readlines()
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
Close the file
f.close()
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
It is safer to use the `with` statement (contexts)
with open("data.csv") as f: raw_data = f.readlines() raw_data f.closed
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
We don't need to close the file, it is done automatically after executing the block of instructions under the `with` statement It is safer because if an error happens within the block of instructions, the file is closed anyway.Note here how we can explicitly raise an Error. There are many kinds of exceptions, see: http...
with open("data.csv") as f: raw_data = f.readlines() raise ValueError("something wrong happened") raw_data f.closed
_____no_output_____
CC-BY-4.0
notebooks/lectures_potsdam_201802/python_intro.ipynb
benbovy/python_short_course
14 - Introduction to Deep Learningby [Alejandro Correa Bahnsen](albahnsen.com/)version 0.1, May 2016 Part of the class [Machine Learning Applied to Risk Management](https://github.com/albahnsen/ML_RiskManagement)This notebook is licensed under a [Creative Commons Attribution-ShareAlike 3.0 Unported License](http://cr...
import numpy as np from load import mnist X_train, X_test, y_train2, y_test2 = mnist(onehot=True) y_train = np.argmax(y_train2, axis=1) y_test = np.argmax(y_test2, axis=1) X_train[1].reshape((28, 28)).round(0).astype(int)[:, 4:26].tolist() from pylab import imshow, show, cm import matplotlib.pylab as plt %matplotlib in...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Naive modelFor each image, find the “most similar” image and guessthat as the label
def similarity(image, images): similarities = [] image = image.reshape((28, 28)) images = images.reshape((-1, 28, 28)) for i in range(images.shape[0]): distance = np.sqrt(np.sum(image - images[i]) ** 2) sim = 1 / distance similarities.append(sim) return similarities np.random...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Lets try an other example
view_image(X_test[200]) similarities = similarity(X_test[200], X_train[small_train]) view_image(X_train[small_train[np.argmax(similarities)]])
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Logistic RegressionLogistic regression is a probabilistic, linear classifier. It is parametrizedby a weight matrix $W$ and a bias vector $b$ Classification isdone by projecting data points onto a set of hyperplanes, the distance towhich is used to determine a class membership probability.Mathematically, this can be wr...
import theano from theano import tensor as T import numpy as np import datetime as dt theano.config.floatX = 'float32'
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
```Theano is a Python library that lets you to define, optimize, and evaluate mathematical expressions, especially ones with multi-dimensional arrays (numpy.ndarray). Using Theano it is possible to attain speeds rivaling hand-crafted C implementations for problems involving large amounts of data. It can also surpass C ...
def floatX(X): # return np.asarray(X, dtype='float32') return np.asarray(X, dtype=theano.config.floatX) def init_weights(shape): return theano.shared(floatX(np.random.randn(*shape) * 0.01)) def model(X, w): return T.nnet.softmax(T.dot(X, w)) X = T.fmatrix() Y = T.fmatrix() w = init_weights((784, 10))...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
initialize model
py_x = model(X, w) y_pred = T.argmax(py_x, axis=1) cost = T.mean(T.nnet.categorical_crossentropy(py_x, Y)) gradient = T.grad(cost=cost, wrt=w) update = [[w, w - gradient * 0.05]] train = theano.function(inputs=[X, Y], outputs=cost, updates=update, allow_input_downcast=True) predict = theano.function(inputs=[X], outputs...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
One iteration
for start, end in zip(range(0, X_train.shape[0], 128), range(128, X_train.shape[0], 128)): cost = train(X_train[start:end], y_train2[start:end]) errors = [(np.mean(y_train != predict(X_train)), np.mean(y_test != predict(X_test)))] errors
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Now for 100 epochs
t0 = dt.datetime.now() for i in range(100): for start, end in zip(range(0, X_train.shape[0], 128), range(128, X_train.shape[0], 128)): cost = train(X_train[start:end], y_train2[start:end]) errors.append((np.mean(y_train != predict(X_train)), ...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Checking the results
y_pred = predict(X_test) np.random.seed(2) small_test = np.random.choice(X_test.shape[0], 10) for i in small_test: view_image(X_test[i], label=y_test[i], predicted=y_pred[i], size=1)
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Simple Neural NetAdd a hidden layer with a sigmoid activation function![a](images/d3.png)
def sgd(cost, params, lr=0.05): grads = T.grad(cost=cost, wrt=params) updates = [] for p, g in zip(params, grads): updates.append([p, p - g * lr]) return updates def model(X, w_h, w_o): h = T.nnet.sigmoid(T.dot(X, w_h)) pyx = T.nnet.softmax(T.dot(h, w_o)) return pyx w_h = init_weig...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Complex Neural NetTwo hidden layers with dropout![a](images/d4.png)
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams srng = RandomStreams() def rectify(X): return T.maximum(X, 0.)
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Understanding rectifier units![A](images/d5.png)
def RMSprop(cost, params, lr=0.001, rho=0.9, epsilon=1e-6): grads = T.grad(cost=cost, wrt=params) updates = [] for p, g in zip(params, grads): acc = theano.shared(p.get_value() * 0.) acc_new = rho * acc + (1 - rho) * g ** 2 gradient_scaling = T.sqrt(acc_new + epsilon) g = g /...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
RMSpropRMSprop is an unpublished, adaptive learning rate method proposed by Geoff Hinton in [Lecture 6e of his Coursera Class](http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)RMSprop and Adadelta have both been developed independently around the same time stemming from the need to resolve Adagr...
def dropout(X, p=0.): if p > 0: retain_prob = 1 - p X *= srng.binomial(X.shape, p=retain_prob, dtype=theano.config.floatX) X /= retain_prob return X def model(X, w_h, w_h2, w_o, p_drop_input, p_drop_hidden): X = dropout(X, p_drop_input) h = rectify(T.dot(X, w_h)) h = dropou...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Convolutional Neural NetworkIn machine learning, a convolutional neural network (CNN, or ConvNet) is a type of feed-forward artificial neural network in which the connectivity pattern between its neurons is inspired by the organization of the animal visual cortex, whose individual neurons are arranged in such a way th...
# from theano.tensor.nnet.conv import conv2d from theano.tensor.nnet import conv2d from theano.tensor.signal.downsample import max_pool_2d
/home/al/anaconda3/lib/python3.5/site-packages/theano/tensor/signal/downsample.py:6: UserWarning: downsample module has been moved to the theano.tensor.signal.pool module. "downsample module has been moved to the theano.tensor.signal.pool module.")
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Modify dropout function
def model(X, w, w2, w3, w4, w_o, p_drop_conv, p_drop_hidden): l1a = rectify(conv2d(X, w, border_mode='full')) l1 = max_pool_2d(l1a, (2, 2)) l1 = dropout(l1, p_drop_conv) l2a = rectify(conv2d(l1, w2)) l2 = max_pool_2d(l2a, (2, 2)) l2 = dropout(l2, p_drop_conv) l3a = rectify(conv2d(l2, w3)) ...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
reshape into conv 4tensor (b, c, 0, 1) format
X_train2 = X_train.reshape(-1, 1, 28, 28) X_test2 = X_test.reshape(-1, 1, 28, 28) # now 4tensor for conv instead of matrix X = T.ftensor4() Y = T.fmatrix() w = init_weights((32, 1, 3, 3)) w2 = init_weights((64, 32, 3, 3)) w3 = init_weights((128, 64, 3, 3)) w4 = init_weights((128 * 3 * 3, 625)) w_o = init_weights((625, ...
_____no_output_____
MIT
notebooks/14_Intro_DeepLearning.ipynb
Torroledo/ML_RiskManagement
Predict batches of images
tf.compat.v1.enable_v2_behavior() label = ['3_24+10', '3_24+30', '3_24+5', '3_24+60', '3_24+70', '3_24+90', '3_24+110', '3_24+20', '3_24+40', '3_24+50', '3_24+80', '1_12_1', '1_12_2', '1_13', '1_14', '1_19', '1_24', '1_26', '1_27', '3_21', '3_31', '3_33', '4_4_1', '4_4_2', '4_5_2', '4_5_4', '4_5_5', '4_8_5', '4_8_6', '...
_____no_output_____
MIT
predict.ipynb
trancongthinh6304/trafficsignclassification
Predict single image
model1= keras.models.load_model("../input/aaaaaaaaaa/VGG19_2.h5") model2= keras.models.load_model("../input/aaaaaaaaaa/InceptionResNetV2_2.h5") model3 = keras.models.load_model('../input/aaaaaaaaaa/denset201_2.h5') def auto_encoder(img_path): img = image.load_img(img_path, target_size=(80,80,3)) img = image.img...
_____no_output_____
MIT
predict.ipynb
trancongthinh6304/trafficsignclassification
ML Project 6033657523 - Feedforward neural network Importing the libraries
from sklearn.metrics import mean_absolute_error from sklearn.svm import SVR from sklearn.model_selection import KFold, train_test_split from math import sqrt import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error, mean_absolute_error import matplotlib.pyplot as plt
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Importing the cleaned dataset
dataset = pd.read_csv('cleanData_Final.csv') X = dataset[['PrevAVGCost', 'PrevAssignedCost', 'AVGCost', 'LatestDateCost', 'A', 'B', 'C', 'D', 'E', 'F', 'G']] y = dataset['GenPrice'] X
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Feedforward neural network Fitting Feedforward neural network to the Training Set
from sklearn.neural_network import MLPRegressor regressor = MLPRegressor(hidden_layer_sizes = (200, 200, 200, 200, 200), activation = 'relu', solver = 'adam', max_iter = 500, learning_rate = 'adaptive') regressor.fit(X_train, y_train) trainSet = pd.concat([X_train, y_train], axis = 1) trainSet.head()
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Evaluate model accuracy
y_pred = regressor.predict(X_test) y_pred testSet = pd.concat([X_test, y_test], axis = 1) testSet.head()
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Compare GenPrice with PredictedGenPrice
datasetPredict = pd.concat([testSet.reset_index(), pd.Series(y_pred, name = 'PredictedGenPrice')], axis = 1).round(2) datasetPredict.head(10) datasetPredict.corr() print("Training set accuracy = " + str(regressor.score(X_train, y_train))) print("Test set accuracy = " + str(regressor.score(X_test, y_test)))
Training set accuracy = 0.9898465392908009 Test set accuracy = 0.9841771850834575
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Training set accuracy = 0.9885445650077587Test set accuracy = 0.9829187423043221 MSE
from sklearn import metrics print('MSE:', metrics.mean_squared_error(y_test, y_pred))
MSE: 160.2404730229541
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
MSE v1: 177.15763887557458MSE v2: 165.73161615532584MSE v3: 172.98494783761967 MAPE
def mean_absolute_percentage_error(y_test, y_pred): y_test, y_pred = np.array(y_test), np.array(y_pred) return np.mean(np.abs((y_test - y_pred)/y_test)) * 100 print('MAPE:', mean_absolute_percentage_error(y_test, y_pred))
MAPE: 6.159884199380194
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
MAPE v1: 6.706572320387714MAPE v2: 6.926678067146115MAPE v3: 7.34081953098462 Visualize
import matplotlib.pyplot as plt plt.plot([i for i in range(len(y_pred))], y_pred, color = 'r') plt.scatter([i for i in range(len(y_pred))], y_test, color = 'b') plt.ylabel('Price') plt.xlabel('Index') plt.legend(['Predict', 'True'], loc = 'best') plt.show()
_____no_output_____
MIT
ML Project Feedforward Neural Network 6033657523.ipynb
bellmcp/machine-learning-price-prediction
Transfer LearningMost of the time you won't want to train a whole convolutional network yourself. Modern ConvNets training on huge datasets like ImageNet take weeks on multiple GPUs. Instead, most people use a pretrained network either as a fixed feature extractor, or as an initial network to fine tune. In this notebo...
from urllib.request import urlretrieve from os.path import isfile, isdir from tqdm import tqdm vgg_dir = 'tensorflow_vgg/' # Make sure vgg exists if not isdir(vgg_dir): raise Exception("VGG directory doesn't exist!") class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_s...
Parameter file already exists!
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
Flower powerHere we'll be using VGGNet to classify images of flowers. To get the flower dataset, run the cell below. This dataset comes from the [TensorFlow inception tutorial](https://www.tensorflow.org/tutorials/image_retraining).
import tarfile dataset_folder_path = 'flower_photos' class DLProgress(tqdm): last_block = 0 def hook(self, block_num=1, block_size=1, total_size=None): self.total = total_size self.update((block_num - self.last_block) * block_size) self.last_block = block_num if not isfile('flower_ph...
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND
ConvNet CodesBelow, we'll run through all the images in our dataset and get codes for each of them. That is, we'll run the images through the VGGNet convolutional layers and record the values of the first fully connected layer. We can then write these to a file for later when we build our own classifier.Here we're usi...
import os import numpy as np import tensorflow as tf from tensorflow_vgg import vgg16 from tensorflow_vgg import utils data_dir = 'flower_photos/' contents = os.listdir(data_dir) classes = [each for each in contents if os.path.isdir(data_dir + each)]
_____no_output_____
MIT
transfer-learning/Transfer_Learning.ipynb
skagrawal/Deep-Learning-Udacity-ND