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 |
|---|---|---|---|---|---|
Script FunctionsSageMaker invokes the main function defined within your training script for training. When deploying your trained model to an endpoint, the model_fn() is called to determine how to load your trained model. The model_fn() along with a few other functions list below are called to enable predictions on Sa... | from sagemaker.pytorch import PyTorch
cifar10_estimator = PyTorch(entry_point='source/cifar10.py',
role=role,
framework_version='1.4.0',
train_instance_count=1,
train_instance_type=instance_type)
cifar10_es... | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Deploy the trained model to prepare for predictionsThe deploy() method creates an endpoint (in this case locally) which serves prediction requests in real-time. | from sagemaker.pytorch import PyTorchModel
cifar10_predictor = cifar10_estimator.deploy(initial_instance_count=1,
instance_type=instance_type) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Invoking the endpoint | # get some test images
dataiter = iter(testloader)
images, labels = dataiter.next()
# print images
imshow(torchvision.utils.make_grid(images))
print('GroundTruth: ', ' '.join('%4s' % classes[labels[j]] for j in range(4)))
outputs = cifar10_predictor.predict(images.numpy())
_, predicted = torch.max(torch.from_numpy(n... | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Clean-upDeleting the local endpoint when you're finished is important, since you can only run one local endpoint at a time. | cifar10_estimator.delete_endpoint() | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Procedural programming in python Topics* Tuples, lists and dictionaries* Flow control, part 1 * If * For * range() function* Some hacky hack time* Flow control, part 2 * Functions TuplesLet's begin by creating a tuple called `my_tuple` that contains three elements. | my_tuple = ('I', 'like', 'cake')
my_tuple | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Tuples are simple containers for data. They are ordered, meaining the order the elements are in when the tuple is created are preserved. We can get values from our tuple by using array indexing, similar to what we were doing with pandas. | my_tuple[0] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Recall that Python indexes start at 0. So the first element in a tuple is 0 and the last is array length - 1. You can also address from the `end` to the `front` by using negative (`-`) indexes, e.g. | my_tuple[-1] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can also access a range of elements, e.g. the first two, the first three, by using the `:` to expand a range. This is called ``slicing``. | my_tuple[0:2]
my_tuple[0:3] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
What do you notice about how the upper bound is referenced? Without either end, the ``:`` expands to the entire list. | my_tuple[1:]
my_tuple[:-1]
my_tuple[:] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Tuples have a key feature that distinguishes them from other types of object containers in Python. They are _immutable_. This means that once the values are set, they cannot change. | my_tuple[2] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
So what happens if I decide that I really prefer pie over cake? | #my_tuple[2] = 'pie' | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Facts about tuples:* You can't add elements to a tuple. Tuples have no append or extend method.* You can't remove elements from a tuple. Tuples have no remove or pop method.* You can also use the in operator to check if an element exists in the tuple.So then, what are the use cases of tuples? * Speed* `Write-protects`... | my_tuple
my_tuple = ('I', 'love', 'pie')
my_tuple | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
There is a really handy operator ``in`` that can be used with tuples that will return `True` if an element is present in a tuple and `False` otherwise. | 'love' in my_tuple | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Finally, tuples can contain different types of data, not just strings. | import math
my_second_tuple = (42, 'Elephants', 'ate', math.pi)
my_second_tuple | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Numerical operators work... Sort of. What happens when you add? ``my_second_tuple + 'plus'`` Not what you expects? What about adding two tuples? | my_second_tuple + my_tuple | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Other operators: -, /, * Questions about tuples before we move on? ListsLet's begin by creating a list called `my_list` that contains three elements. | my_list = ['I', 'like', 'cake']
my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
At first glance, tuples and lists look pretty similar. Notice the lists use '[' and ']' instead of '(' and ')'. But indexing and refering to the first entry as 0 and the last as -1 still works the same. | my_list[0]
my_list[-1]
my_list[0:3] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Lists, however, unlike tuples, are mutable. | my_list[2] = 'pie'
my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Multiple elements in the list can even be changed at once! | my_list[1:] = ['love', 'puppies']
my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can still use the `in` operator. | 'puppies' in my_list
'kittens' in my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
So when to use a tuple and when to use a list?* Use a list when you will modify it after it is created?Ways to modify a list? You have already seen by index. Let's start with an empty list. | my_new_list = []
my_new_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
We can add to the list using the append method on it. | my_new_list.append('Now')
my_new_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
We can use the `+` operator to create a longer list by adding the contents of two lists together. | my_new_list + my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
One of the useful things to know about a list how many elements are in it. This can be found with the `len` function. | len(my_list) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Some other handy functions with lists:* max* min* cmp Sometimes you have a tuple and you need to make it a list. You can `cast` the tuple to a list with ``list(my_tuple)`` | list(my_tuple) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
What in the above told us it was a list? You can also use the ``type`` function to figure out the type. | type(tuple)
type(list(my_tuple)) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
There are other useful methods on lists, including:| methods | description ||---|---|| list.append(obj) | Appends object obj to list || list.count(obj)| Returns count of how many times obj occurs in list || list.extend(seq) | Appends the contents of seq to list || list.index(obj) | Returns the lowest index in ... | my_list.count('I')
my_list
my_list.append('I')
my_list
my_list.count('I')
my_list
#my_list.index(42)
my_list.index('puppies')
my_list
my_list.insert(my_list.index('puppies'), 'furry')
my_list
my_list.pop()
my_list
my_list.remove('puppies')
my_list
my_list.append('cabbages')
my_list | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Any questions about lists before we move on? DictionariesDictionaries are similar to tuples and lists in that they hold a collection of objects. Dictionaries, however, allow an additional indexing mode: keys. Think of a real dictionary where the elements in it are the definitions of the words and the keys to retrie... | my_dict = { 'tuple' : 'An immutable collection of ordered objects',
'list' : 'A mutable collection of ordered objects',
'dictionary' : 'A mutable collection of objects' }
my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
We access items in the dictionary by name, e.g. | my_dict['dictionary'] | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Since the dictionary is mutable, you can change the entries. | my_dict['dictionary'] = 'A mutable collection of named objects'
my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Notice that ordering is not preserved! As of Python 3.7 the ordering is garunteed to be insertion order but that does not mean alphabetical or otherwise sorted.And we can add new items to the list. | my_dict['cabbage'] = 'Green leafy plant in the Brassica family'
my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
To delete an entry, we can't just set it to ``None`` | my_dict['cabbage'] = None
my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
To delete it propery, we need to pop that specific entry. | my_dict.pop('cabbage', None)
my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can use other objects as names, but that is a topic for another time. You can mix and match key types, e.g. | my_new_dict = {}
my_new_dict[1] = 'One'
my_new_dict['42'] = 42
my_new_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can get a list of keys in the dictionary by using the ``keys`` method. | my_dict.keys() | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Similarly the contents of the dictionary with the ``items`` method. | my_dict.items() | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
We can use the keys list for fun stuff, e.g. with the ``in`` operator. | 'dictionary' in my_dict.keys() | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
This is a synonym for `in my_dict` | 'dictionary' in my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Notice, it doesn't work for elements. | 'A mutable collection of ordered objects' in my_dict | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Other dictionary methods:| methods | description ||---|---|| dict.clear() | Removes all elements from dict || dict.get(key, default=None) | For ``key`` key, returns value or ``default`` if key doesn't exist in dict | | dict.items() | Returns a list of dicts (key, value) tuple pairs | | dict.keys() | Returns a list o... | instructors = ['Dave', 'Jim', 'Dorkus the Clown']
instructors | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
IfIf statements can be use to execute some lines or block of code if a particular condition is satisfied. E.g. Let's print something based on the entries in the list. | if 'Dorkus the Clown' in instructors:
print('#fakeinstructor') | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Usually we want conditional logic on both sides of a binary condition, e.g. some action when ``True`` and some when ``False`` | if 'Dorkus the Clown' in instructors:
print('There are fake names for class instructors in your list!')
else:
print("Nothing to see here") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
There is a special do nothing word: `pass` that skips over some arm of a conditional, e.g. | if 'Jim' in instructors:
print("Congratulations! Jim is teaching, your class won't stink!")
else:
pass | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
_Note_: what have you noticed in this session about quotes? What is the difference between ``'`` and ``"``?Another simple example: | if True is False:
print("I'm so confused")
else:
print("Everything is right with the world") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
It is always good practice to handle all cases explicity. `Conditional fall through` is a common source of bugs.Sometimes we wish to test multiple conditions. Use `if`, `elif`, and `else`. | my_favorite = 'pie'
if my_favorite is 'cake':
print("He likes cake! I'll start making a double chocolate velvet cake right now!")
elif my_favorite is 'pie':
print("He likes pie! I'll start making a cherry pie right now!")
else:
print("He likes " + my_favorite + ". I don't know how to make that.") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Conditionals can take ``and`` and ``or`` and ``not``. E.g. | my_favorite = 'pie'
if my_favorite is 'cake' or my_favorite is 'pie':
print(my_favorite + " : I have a recipe for that!")
else:
print("Ew! Who eats that?") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
ForFor loops are the standard loop, though `while` is also common. For has the general form:```for items in list: do stuff```For loops and collections like tuples, lists and dictionaries are natural friends. | for instructor in instructors:
print(instructor) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can combine loops and conditionals: | for instructor in instructors:
if instructor.endswith('Clown'):
print(instructor + " doesn't sound like a real instructor name!")
else:
print(instructor + " is so smart... all those gooey brains!") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Dictionaries can use the `keys` method for iterating. | for key in my_dict.keys():
if len(key) > 5:
print(my_dict[key]) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
range()Since for operates over lists, it is common to want to do something like:```NOTE: C-likefor (i = 0; i < 3; ++i) { print(i);}```The Python equivalent is:```for i in [0, 1, 2]: do something with i```What happens when the range you want to sample is big, e.g.```NOTE: C-likefor (i = 0; i < 1000000000; ++i) { ... | range(3) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Notice that Python (in the newest versions, e.g. 3+) has an object type that is a range. This saves memory and speeds up calculations vs. an explicit representation of a range as a list - but it can be automagically converted to a list on the fly by Python. To show the contents as a `list` we can use the type case li... | list(range(3)) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Remember earlier with slicing, the syntax `:3` meant `[0, 1, 2]`? Well, the same upper bound philosophy applies here. | for index in range(3):
instructor = instructors[index]
if instructor.endswith('Clown'):
print(instructor + " doesn't sound like a real instructor name!")
else:
print(instructor + " is so smart... all those gooey brains!") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
This would probably be better written as | for index in range(len(instructors)):
instructor = instructors[index]
if instructor.endswith('Clown'):
print(instructor + " doesn't sound like a real instructor name!")
else:
print(instructor + " is so smart... all those gooey brains!") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
But in all, it isn't very Pythonesque to use indexes like that (unless you have another reason in the loop) and you would opt instead for the `instructor in instructors` form. More often, you are doing something with the numbers that requires them to be integers, e.g. math. | sum = 0
for i in range(10):
sum += i
print(sum) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
For loops can be nested_Note_: for more on formatting strings, see: [https://pyformat.info](https://pyformat.info) | for i in range(1, 4):
for j in range(1, 4):
print('%d * %d = %d' % (i, j, i*j)) # Note string formatting here, %d means an integer | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can exit loops early if a condition is met: | for i in range(10):
if i == 4:
break
i | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can skip stuff in a loop with `continue` | sum = 0
for i in range(10):
if (i == 5):
continue
else:
sum += i
print(sum) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
There is a unique language feature call ``for...else`` | sum = 0
for i in range(10):
sum += i
else:
print('final i = %d, and sum = %d' % (i, sum)) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
You can iterate over letters in a string | my_string = "DIRECT"
for c in my_string:
print(c) | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Hacky Hack Time with Ifs, Fors, Lists, and imports!Objective: Replace the `bash magic` bits for downloading the HCEPDB data and uncompressing it with Python code. Since the download is big, check if the zip file exists first before downloading it again. Then load it into a pandas dataframe.Notes:* The `os` package h... | def print_string(str):
"""This prints out a string passed as the parameter."""
print(str)
return | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
To call the function, use:```print_string("Dave is awesome!")```_Note:_ The function has to be defined before you can call it! | print_string("Dave is awesome!") | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
If you don't provide an argument or too many, you get an error. Parameters (or arguments) in Python are all passed by reference. This means that if you modify the parameters in the function, they are modified outside of the function.See the following example:```def change_list(my_list): """This changes a passed list... | def change_list(my_list):
"""This changes a passed list into this function"""
my_list.append('four');
print('list inside the function: ', my_list)
return
my_list = [1, 2, 3];
print('list before the function: ', my_list)
change_list(my_list);
print('list after the function: ', my_list) | list before the function: [1, 2, 3]
list inside the function: [1, 2, 3, 'four']
list after the function: [1, 2, 3, 'four']
| BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Variables have scope: `global` and `local`In a function, new variables that you create are not saved when the function returns - these are `local` variables. Variables defined outside of the function can be accessed but not changed - these are `global` variables, _Note_ there is a way to do this with the `global` keyw... | def print_name(first, last='the Clown'):
print('Your name is %s %s' % (first, last))
return | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Play around with the above function. Functions can contain any code that you put anywhere else including:* if...elif...else* for...else* while* other function calls | def print_name_age(first, last, age):
print_name(first, last)
print('Your age is %d' % (age))
if age > 35:
print('You are really old.')
return
print_name_age(age=40, last='Beck', first='Dave') | _____no_output_____ | BSD-3-Clause | Wi20_content/SEDS/L5.Procedural_Python.ipynb | ShahResearchGroup/UWDIRECT.github.io |
Lomb-Scargle Example Dataset The DataFor simplicity, we download the data here and save locally | import pandas as pd
def get_LINEAR_lightcurve(lcid):
from astroML.datasets import fetch_LINEAR_sample
LINEAR_sample = fetch_LINEAR_sample()
data = pd.DataFrame(LINEAR_sample[lcid],
columns=['t', 'mag', 'magerr'])
data.to_csv('LINEAR_{0}.csv'.format(lcid), index=False)
# Uncom... | _____no_output_____ | CC-BY-4.0 | figures/LINEAR_Example.ipynb | spencerwplovie/Lomb-Scargle-Copied |
Visualizing the Data | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.style.use('seaborn-whitegrid')
fig, ax = plt.subplots(figsize=(8, 3))
ax.errorbar(data.t, data.mag, data.magerr,
fmt='.k', ecolor='gray', capsize=0)
ax.set(xlabel='time (MJD)',
ylabel='magnitude',
ti... | _____no_output_____ | CC-BY-4.0 | figures/LINEAR_Example.ipynb | spencerwplovie/Lomb-Scargle-Copied |
Peak PrecisionEstimate peak precision by plotting the Bayesian periodogram peak and fitting a Gaussian to the peak (for simplicity, just do it by-eye): | f, P = ls.autopower(nyquist_factor=500,
minimum_frequency=9.3,
maximum_frequency=9.31,
samples_per_peak=20,
normalization='psd')
P = np.exp(P)
P /= P.max()
h = 24. / f
plt.plot(h, P, '-k')
plt.fill(h, np.exp(-0.5 * (h - 2.58014) ** 2 / 0.0... | /Users/jakevdp/anaconda/envs/python3.5/lib/python3.5/site-packages/ipykernel/__main__.py:6: RuntimeWarning: overflow encountered in exp
/Users/jakevdp/anaconda/envs/python3.5/lib/python3.5/site-packages/ipykernel/__main__.py:7: RuntimeWarning: invalid value encountered in true_divide
| CC-BY-4.0 | figures/LINEAR_Example.ipynb | spencerwplovie/Lomb-Scargle-Copied |
Looks like $2.58023 \pm 0.00006$ hours | fig, ax = plt.subplots(figsize=(10, 3))
phase_model = np.linspace(-0.5, 1.5, 100)
best_frequency = frequency[np.argmax(power)]
mag_model = ls.model(phase_model / best_frequency, best_frequency)
for offset in [-1, 0, 1]:
ax.errorbar(phase + offset, data.mag, data.magerr, fmt='.',
color='gray', ecol... | _____no_output_____ | CC-BY-4.0 | figures/LINEAR_Example.ipynb | spencerwplovie/Lomb-Scargle-Copied |
Required Grid Spacing | !head LINEAR_11375941.csv
n_digits = 6
f_ny = 0.5 * 10 ** n_digits
T = (data.t.max() - data.t.min())
n_o = 5
delta_f = 1. / n_o / T
print("f_ny =", f_ny)
print("T =", T)
print("n_grid =", f_ny / delta_f) | f_ny = 500000.0
T = 1961.847365
n_grid = 4904618412.5
| CC-BY-4.0 | figures/LINEAR_Example.ipynb | spencerwplovie/Lomb-Scargle-Copied |
Building your Deep Neural Network: Step by StepWelcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want!- In this notebook, you will implement all the functions re... | import numpy as np
import h5py
import matplotlib.pyplot as plt
from testCases_v4 import *
from dnn_utils_v2 import sigmoid, sigmoid_backward, relu, relu_backward
%matplotlib inline
plt.rcParams['figure.figsize'] = (5.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['imag... | C:\Users\korra\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
from ._conv import register_converters as _register_converters
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
2 - Outline of the AssignmentTo build your neural network, you will be implementing several "helper functions". These helper functions will be used in the next assignment to build a two-layer neural network and an L-layer neural network. Each small helper function you will implement will have detailed instructions tha... | # GRADED FUNCTION: initialize_parameters
def initialize_parameters(n_x, n_h, n_y):
"""
Argument:
n_x -- size of the input layer
n_h -- size of the hidden layer
n_y -- size of the output layer
Returns:
parameters -- python dictionary containing your parameters:
W1 --... | W1 = [[ 0.01624345 -0.00611756 -0.00528172]
[-0.01072969 0.00865408 -0.02301539]]
b1 = [[0.]
[0.]]
W2 = [[ 0.01744812 -0.00761207]]
b2 = [[0.]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected output**: **W1** [[ 0.01624345 -0.00611756 -0.00528172] [-0.01072969 0.00865408 -0.02301539]] **b1** [[ 0.] [ 0.]] **W2** [[ 0.01744812 -0.00761207]] **b2** [[ 0.]] 3.2 - L-layer Neural NetworkThe initialization for a deeper L-layer neural n... | # GRADED FUNCTION: initialize_parameters_deep
def initialize_parameters_deep(layer_dims):
"""
Arguments:
layer_dims -- python array (list) containing the dimensions of each layer in our network
Returns:
parameters -- python dictionary containing your parameters "W1", "b1", ..., "WL", "bL":
... | W1 = [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388]
[-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218]
[-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034]
[-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]]
b1 = [[0.]
[0.]
[0.]
[0.]]
W2 = [[-0.01185047 -0.0020565 ... | MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected output**: **W1** [[ 0.01788628 0.0043651 0.00096497 -0.01863493 -0.00277388] [-0.00354759 -0.00082741 -0.00627001 -0.00043818 -0.00477218] [-0.01313865 0.00884622 0.00881318 0.01709573 0.00050034] [-0.00404677 -0.0054536 -0.01546477 0.00982367 -0.01101068]] **b1** [[ 0... | # GRADED FUNCTION: linear_forward
def linear_forward(A, W, b):
"""
Implement the linear part of a layer's forward propagation.
Arguments:
A -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (size of current la... | Z = [[ 3.26295337 -1.23429987]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected output**: **Z** [[ 3.26295337 -1.23429987]] 4.2 - Linear-Activation ForwardIn this notebook, you will use two activation functions:- **Sigmoid**: $\sigma(Z) = \sigma(W A + b) = \frac{1}{ 1 + e^{-(W A + b)}}$. We have provided you with the `sigmoid` function. This function returns **two** ... | # GRADED FUNCTION: linear_activation_forward
def linear_activation_forward(A_prev, W, b, activation):
"""
Implement the forward propagation for the LINEAR->ACTIVATION layer
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weigh... | With sigmoid: A = [[0.96890023 0.11013289]]
With ReLU: A = [[3.43896131 0. ]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected output**: **With sigmoid: A ** [[ 0.96890023 0.11013289]] **With ReLU: A ** [[ 3.43896131 0. ]] **Note**: In deep learning, the "[LINEAR->ACTIVATION]" computation is counted as a single layer in the neural network, not two layers. d) L-Layer Model For even more c... | # GRADED FUNCTION: L_model_forward
def L_model_forward(X, parameters):
"""
Implement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation
Arguments:
X -- data, numpy array of shape (input size, number of examples)
parameters -- output of initialize_parameters_deep()
... | AL = [[0.03921668 0.70498921 0.19734387 0.04728177]]
Length of caches list = 3
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**AL** [[ 0.03921668 0.70498921 0.19734387 0.04728177]] **Length of caches list ** 3 Great! Now you have a full forward propagation that takes the input X and outputs a row vector $A^{[L]}$ containing your predictions. It also records all intermediate values in "caches". Using $A^{[L]}$... | # GRADED FUNCTION: compute_cost
def compute_cost(AL, Y):
"""
Implement the cost function defined by equation (7).
Arguments:
AL -- probability vector corresponding to your label predictions, shape (1, number of examples)
Y -- true "label" vector (for example: containing 0 if non-cat, 1 if cat), sh... | cost = 0.41493159961539694
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected Output**: **cost** 0.41493159961539694 6 - Backward propagation moduleJust like with forward propagation, you will implement helper functions for backpropagation. Remember that back propagation is used to calculate the gradient of the loss function with respect to the parameters. **Reminder... | # GRADED FUNCTION: linear_backward
def linear_backward(dZ, cache):
"""
Implement the linear portion of backward propagation for a single layer (layer l)
Arguments:
dZ -- Gradient of the cost with respect to the linear output (of current layer l)
cache -- tuple of values (A_prev, W, b) coming from ... | dA_prev = [[ 0.51822968 -0.19517421]
[-0.40506361 0.15255393]
[ 2.37496825 -0.89445391]]
dW = [[-0.10076895 1.40685096 1.64992505]]
db = [[0.50629448]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected Output**: **dA_prev** [[ 0.51822968 -0.19517421] [-0.40506361 0.15255393] [ 2.37496825 -0.89445391]] **dW** [[-0.10076895 1.40685096 1.64992505]] **db** [[ 0.50629448]] 6.2 - Linear-Activation backwardNext, you will create a... | # GRADED FUNCTION: linear_activation_backward
def linear_activation_backward(dA, cache, activation):
"""
Implement the backward propagation for the LINEAR->ACTIVATION layer.
Arguments:
dA -- post-activation gradient for current layer l
cache -- tuple of values (linear_cache, activation_cache)... | sigmoid:
dA_prev = [[ 0.11017994 0.01105339]
[ 0.09466817 0.00949723]
[-0.05743092 -0.00576154]]
dW = [[ 0.10266786 0.09778551 -0.01968084]]
db = [[-0.05729622]]
relu:
dA_prev = [[ 0.44090989 -0. ]
[ 0.37883606 -0. ]
[-0.2298228 0. ]]
dW = [[ 0.44513824 0.37371418 -0.10478989]]
db = [[-0... | MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected output with sigmoid:** dA_prev [[ 0.11017994 0.01105339] [ 0.09466817 0.00949723] [-0.05743092 -0.00576154]] dW [[ 0.10266786 0.09778551 -0.01968084]] db [[-0.05729622]] **Expected output with relu:** dA_prev ... | # GRADED FUNCTION: L_model_backward
def L_model_backward(AL, Y, caches):
"""
Implement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group
Arguments:
AL -- probability vector, output of the forward propagation (L_model_forward())
Y -- true "label" vector (contain... | dW1 = [[0.41010002 0.07807203 0.13798444 0.10502167]
[0. 0. 0. 0. ]
[0.05283652 0.01005865 0.01777766 0.0135308 ]]
db1 = [[-0.22007063]
[ 0. ]
[-0.02835349]]
dA1 = [[ 0.12913162 -0.44014127]
[-0.14175655 0.48317296]
[ 0.01663708 -0.05670698]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
**Expected Output** dW1 [[ 0.41010002 0.07807203 0.13798444 0.10502167] [ 0. 0. 0. 0. ] [ 0.05283652 0.01005865 0.01777766 0.0135308 ]] db1 [[-0.22007063] [ 0. ] [-0.02835349]] dA1 [[ 0.12913162 -0.44... | # GRADED FUNCTION: update_parameters
def update_parameters(parameters, grads, learning_rate):
"""
Update parameters using gradient descent
Arguments:
parameters -- python dictionary containing your parameters
grads -- python dictionary containing your gradients, output of L_model_backward
... | W1 = [[-0.59562069 -0.09991781 -2.14584584 1.82662008]
[-1.76569676 -0.80627147 0.51115557 -1.18258802]
[-1.0535704 -0.86128581 0.68284052 2.20374577]]
b1 = [[-0.04659241]
[-1.28888275]
[ 0.53405496]]
W2 = [[-0.55569196 0.0354055 1.32964895]]
b2 = [[-0.84610769]]
| MIT | Course1_week4_Building your Deep Neural Network - Step by Step v8.ipynb | korra0501/deeplearning.ai-coursera |
Data Structures and Algorithms Andres Castellano June 11, 2020 Mini Project 1 | from google.colab import drive
drive.mount('/content/gdrive/')
%cd /content/gdrive/My\ Drive/Mini-Project 1 | _____no_output_____ | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 1)** Construct a text file that follows the input specifications of the problem, i.e. it can serveas a sample input. Specifically, you should give an input file representing a 10x10 patch. The patchshould contain two or three islands, according to your choice. The shape of the islands can bearbitrary, but try to... | f = open('andres-castellano.txt', 'r')
def Coordinates(file):
''' This function will return a list,
where each element of the list is a list itself of coordinates for each test case in the file.
In the case where the input file only contains 1 test case, the function will return a list of length 1... | Number of test cases is: 2
For test case 1 ...
Dimensions are 10 by 10
For test case 2 ...
Dimensions are 20 by 20
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 3)** Write a function CoordinateToNumber(i, j, m, n) that takes a coordinate (i, j) andmaps it to a unique number t in [0, mn − 1], which is then returned by the function.I'm assuming this step is directing us to create a function that takes a list of coordinates and generates unique identifiers for each coordin... | def CoordinateToNumber(coordinate_list=list,m=int,n=int):
'''Returns a list for a list of coordinates as input,
returns a tuple for a coordinate as input'''
global T
if len(coordinate_list) > m*n:
raise Exception('Stop, too many coordinates for mXn')
if type(coordinate_list) is tuple:
... | Number of test cases is: 2
For test case 1 ...
Dimensions are 10 by 10
For test case 2 ...
Dimensions are 20 by 20
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 4)** Write a function NumberToCoordinate(t, m, n) that takes a number t and returns thecorresponding coordinate. This function must be the inverse of CoordinateToNumber. Thatis, for all i, j, m, n we must haveNumberToCoordinate(CoordinateToNumber(i, j, m, n), m, n) = (i, j)The two steps above mean that besides i... | def NumberToCoordinate(L=list,m=int,n=int):
'''Returns a list size n of tuples for a list of inputs of size n'''
coordinate_list = []
for key in L:
coordinate_list.append(T.get(key))
return coordinate_list
NumberToCoordinate(CoordinateToNumber(Coordinates(f)[0],10,10),10,10) | Number of test cases is: 2
For test case 1 ...
Dimensions are 10 by 10
For test case 2 ...
Dimensions are 20 by 20
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
Note 1:The functions as defined above take as inputs iterable objects as seen above. However. All functions can also be called on specific coordinates.For example:The below code will call the identifier and coordinates of one single cell from test case 1. | Coordinates(f)[0][5] # Gets the 6th coordinate of test case 1.
CoordinateToNumber(Coordinates(f)[0][5],10,10) # Gets the identifier and coordinates for the 6th coordinate of case 1.
NumberToCoordinate(CoordinateToNumber(Coordinates(f)[0][5],10,10),10,10)
| Number of test cases is: 2
For test case 1 ...
Dimensions are 10 by 10
For test case 2 ...
Dimensions are 20 by 20
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
The last line of code gets the coordinate from the correspondng identifier given to the coordinate 6 of test case 1.Note that Coordinates(f)[0][5] and NumberToCoordinate(CoordinateToNumber(Coordinates(f)[0][5])) should returnthe same coordinate and it does.**Step 5)** Write a function Distance(t1, t2), where t1 and t2 ... | CoordinateToNumber(Coordinates(f)[0],10,10)
def Distance(t1=int,t2=int):
'''Returns a scalar representing the manhattan distance between two coordinates representing input identifiers t1 and t2. '''
t1 = T[t1]
t2 = T[t2]
distance = abs(t2[1]-t1[1]) + abs(t2[0]-t1[0])
return distance
Dista... | _____no_output_____ | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
Recall that in **Step 2** we wrote a function for finding the list of land cells. Let’s callthis function **FindLandCells**, and its output **LandCell_List**. This list of land cells can looklike this:LandCell List = [10, 11, 25, 12, 50, 51, 80, 81, 82](this is only an example, it does not correspond to some specific ... | FindLandCells = CoordinateToNumber
LandCell_List = CoordinateToNumber(Coordinates(f)[1],20,20)
LandCell_List.keys() | Number of test cases is: 2
For test case 1 ...
Dimensions are 10 by 10
For test case 2 ...
Dimensions are 20 by 20
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
Now this lists can be further broken into islands. So, we have something that looks like this:Island_List = [[10, 11, 12], [25], [50, 51], [80, 81, 82]]You see how all the cells from the original list appear in the second data structure, which is a listof lists, with each list being an island. Observe how cells belongi... | CoordinateToNumber(Coordinates(f)[0],10,10)
def GenerateNeighbors(t1=int,m=int,n=int):
coordinates = T[t1]
row_neighboors = []
candidates = []
row_candidates = [(coordinates[0],coordinates[1]-1),(coordinates[0],coordinates[1]+1)]
[candidates.append(x) for x in row_candidates]
... | _____no_output_____ | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 7)** Write a function ExploreIsland(t1, n, m). This function should start from cell t1,and construct a list of cells that are in the same island as t1. (Hint: t1 can add itself to adictionary representing the island, and also its neighbors, then the neighbors should recursivelydo the the same. But when new neigh... | FindLandCells = CoordinateToNumber
LandCell_List = CoordinateToNumber(Coordinates(f)[0],10,10)
LandCell_List.keys()
def ExploreIsland(t1=int,m=int,n=int, neighbors=[]):
coordinates = T[t1]
candidates = []
if neighbors == []:
neighbors.append(t1)
row_candidates = [(coordinates[0],coordi... |
For Land 0 with coordinates (3, 10), Candidates are [(3, 9), (3, 11), (2, 10), (4, 10)]
...Checking coordinates (3, 9) for land 0
...Checking coordinates (3, 11) for land 0
...Adding land 1 with coordinates (3, 11) to land 0
Exploring land 1____________
For Land 1 with coordinates (3, 11), Candidates ar... | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 8)** Write a function FindIslands that reads the list LandCell_List and converts its toIsland List as explained above. The idea for this step is to scan the list of land cells, and callrepeatedly the ExploreIsland function. | def FindIslands(LandCell_List=list):
Island_List = []
island = []
checked = []
for i in LandCell_List.keys():
if i not in checked:
print("Finding Islands Connected to Land {}".format(i))
island = ExploreIsland(i,20,20,neighbors=[])... | _____no_output_____ | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 9)** Write a function Island Distance(isl1, isl2), which takes two lists of cells representingtwo islands, and finds the distance of these two islands. For this you will need to compute theDistance function from Milestone 1. | def Island_Distance(isl1=list,isl2=list):
x0 = 'nothing'
for i in isl1:
if GenerateNeighbors(i,m=int,n=int) > 3: #Landlocked Land
next
else:
#print(" Checking land {}".format(i))
for j in isl2:
... | _____no_output_____ | MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Step 10)** We will now construct a graph of islands. Consider an example for this. SupposeIsland List contains 3 islands. We will assign to each island a unique number in [0, 3). ThenIsland Graph will be a list of the following form:[[0, 1, d(0, 1)], [0, 2, d(0, 2)], [1, 2, d(1, 2)]].Here d(i, j) is the distance betw... | def Island_Graph(Island_List=list):
import sys, os
# For n islands in Island list, enumerate island on [0,3)
output = []
skip = []
global dums
dums = dict(val for val in enumerate(Island_List))
for i in dums.keys():
#print(i)
skip.append(i)
... |
Lenght of output list is 21, which makes sense for a list of size 7, Since 7 times 6 divided by 2 is 21.0.
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
**Final Step** We now have a data structure which is the adjacency list (with weights) of the graphs.To connect all islands, we need to find a **minimum weight spanning tree** for this graph. Ihave seen one algorithm for computing such a tree in class. However, for this project, I willuse the python library **networkx*... | import networkx as nx
G = nx.Graph()
G.clear()
for i in range(len(fun)):
print(fun[i][0],fun[i][1],fun[i][2])
G.add_edge(fun[i][0],fun[i][1], weight=fun[i][2])
mst = nx.tree.minimum_spanning_edges(G, algorithm='kruskal', data=False)
edgelist = list(mst)
sorted(sorted(e) for e in edgelist)
arbol = sorted(s... | The minimum cost to build the bridges required to connect all the islands is 23.
| MIT | Connect The Islands.ipynb | ac547/Connect-The-Islands |
from google.colab import drive
drive.mount('/content/drive') | Mounted at /content/drive
| MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes | |
Dataset Exploration1. Head of dataset2. Check for null values (absent)3. Check for class imbalance (present - remove it by upsampling) | # Read the csv file
import pandas as pd
df=pd.read_csv('/content/drive/My Drive/Diabetes/diabetes.csv')
df.head()
# Print the null values of every column
df.isna().sum()
# Print class count to check for imbalance
df['Outcome'].value_counts()
from sklearn.utils import resample
df_majority = df[df.Outcome==0]
df_minorit... | 1 500
0 500
Name: Outcome, dtype: int64
| MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Stratified K Folds Cross Validation | # Add a "kfolds" column which will indicate the validation set number
df['kfolds']=-1
# Shuffle all the rows and then reset the index
df=df.sample(frac=1,random_state=42).reset_index(drop=True)
df.head()
from sklearn import model_selection
# Create 5 sets of training,validation sets
strat_kf=model_selection.Stratifie... | _____no_output_____ | MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Scale the features using StandardScaler | from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
df_2=pd.DataFrame(scaler.fit_transform(df),index=df.index,columns=df.columns)
# Target column and kfolds column dont need to be scaled
df_2['Outcome']=df['Outcome']
df_2['kfolds']=df['kfolds']
df_2.head() | _____no_output_____ | MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Feature Selection1. KNN2. Naive Bayes | from sklearn import metrics
import matplotlib.pyplot as plt
def run(fold,df,models,print_details=False):
# Training and validation sets
df_train=df[df['kfolds']!=fold].reset_index(drop=True)
df_valid=df[df['kfolds']==fold].reset_index(drop=True)
# x and y of training dataset
x_train=df_train.drop('Outcom... | _____no_output_____ | MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Greedy Feature Selection | def greedy_feature_selection(fold,df,models,target_name):
# target_index => stores the index of the target variable in the dataset
# kfolds_index => stores the index of kfolds column in the dataset
target_index=df.columns.get_loc(target_name)
kfolds_index=df.columns.get_loc('kfolds')
# good_features => stor... | _____no_output_____ | MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Recursive Feature Selection | from sklearn.feature_selection import RFE
def recursive_feature_selection(df,models,n_features_to_select,target_name):
X=df.drop(labels=[target_name,'kfolds'],axis=1).values
y=df[target_name]
kfolds=df.kfolds.values
model_name,model_constructor=list(models.items())[0]
rfe=RFE(
estimator=model_constru... | Glucose Pregnancies BMI Outcome kfolds
0 -0.230248 -0.053578 -0.363725 1 0
1 2.011697 0.787960 0.691889 1 0
2 -0.614581 1.068473 1.430819 1 0
3 -0.518498 1.629498 -0.007455 1 0
4 0.250169 -1.175629 -0.007455 0 0
Naive ... | MIT | Diabetes.ipynb | AryanMethil/Diabetes-KNN-vs-Naive-Bayes |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.