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
**Question 3.4.** Companies pay executives in a variety of ways: in cash, by granting stock or other equity in the company, or with ancillary benefits (like private jets). Compute the proportion of each CEO's pay that was cash. (Your answer should be an array of numbers, one for each CEO in the dataset.)*Note:* When ...
cash_proportion = ... cash_proportion grader.check("q34")
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
Check out the `% Change` column in `compensation`. It shows the percentage increase in the CEO's pay from the previous year. For CEOs with no previous year on record, it instead says "(No previous year)". The values in this column are *strings*, not numbers, so like the `Total Pay` column, it's not usable without a ...
# Definition to turn percent to number def percent_string_to_num(percent_string): """Converts a percentage string to a number.""" return ... # Compensation table where there is a previous year having_previous_year = ... # Get the percent changes as numbers instead of strings # We're still working off the tabl...
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
**Question 3.6.** What was the average pay of these CEOs in 2014?<!--BEGIN QUESTIONname: q36-->
average_pay_2014 = np.average(with_previous_compensation.column("2014 Total Pay ($)")) average_pay_2014 grader.check("q36")
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
**Why is `apply` useful?**For operations like arithmetic, or the functions in the NumPy library, you don't need to use `apply`, because they automatically work on each element of an array. But there are many things that don't. The string manipulation we did in today's lab is one example. Since you can write any code...
...
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
**Question 4.2.** How many CEOs made more than $30 million in total pay? Find the value using code, then check that the value you found is consistent with what you see in the histogram.*Hint:* Use the table method `where` and the property `num_rows`.<!--BEGIN QUESTIONname: q42-->
num_ceos_more_than_30_million_2 = compensation.where("Total Pay ($)", are.above(30000000)).num_rows num_ceos_more_than_30_million_2 grader.check("q42")
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
5. Project 1 Partner FormProject 1 will be released this Friday! You have the option of working with a partner that is enrolled in your lab. Your GSI will be sending out a form to match you up with a partner for this project. You may also indicate if you're working alone or have already found a partner and do not need...
submitted = ... grader.check("q5")
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
Great job! You're finished with lab 4! Be sure to...* **run all the tests** (the next cell has a shortcut for that),* **Save and Checkpoint** from the File menu,* **run the last cell to submit your work**,* and **ask one of the staff members to check you off**. ---To double-check your work, the cell below will rerun al...
grader.check_all()
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
SubmissionMake sure you have run all cells in your notebook in order before running the cell below, so that all images/graphs appear in the output. The cell below will generate a zip file for you to submit. **Please save before exporting!**
# Save your notebook first, then run this cell to export your submission. grader.export()
_____no_output_____
BSD-3-Clause
lab/lab04/.ipynb_checkpoints/lab04-checkpoint.ipynb
ds-modules/Colab-demo
Assign value of B = 1000 where C = 1 & D = -1 &
df2 = df df2.loc[df2.D.eq(-1), 'B'] = 1000 df2.head(5) df3 = df df3.loc[df3.D.eq(-1) & df3.C.eq(1), 'B'] = 1000 df3.head(5)
_____no_output_____
MIT
notebooks/pandas/df_assign_col_values.ipynb
codenamewei/pydata-science-playground
this works, but with warnings
df1 = df df1[df1.D == -1].B = 1000 df1.head(5)
C:\Users\codenamewei\.conda\envs\data-science-playground\lib\site-packages\pandas\core\generic.py:5494: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pan...
MIT
notebooks/pandas/df_assign_col_values.ipynb
codenamewei/pydata-science-playground
Use .loc[row_indexer,col_indexer] = value instead This works, but with warning
df_ = df df_.iloc[df_.loc[df_.D == -1].index[0]].B = 1000 df_.head(5)
C:\Users\codenamewei\.conda\envs\data-science-playground\lib\site-packages\pandas\core\generic.py:5494: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view...
MIT
notebooks/pandas/df_assign_col_values.ipynb
codenamewei/pydata-science-playground
Aux Functions
def generateDates(start=date(2019, 1, 1), end=date(2019, 8, 31), delta=timedelta(days=1), strFormat=""): curr = start dates = [] while curr < end: if strFormat == "": dates.append(str(curr)) else: dates.append(curr.strftime(strFormat)) curr += delta return...
Url-Base: https://elpais.com/hemeroteca/elpais/{date}/{partOfDay}/portada.html -> urlsPerDay length: 3 -> urlsPerDay length: 6 -> urlsPerDay length: 9 -> urlsPerDay length: 12 -> urlsPerDay length: 15 -> urlsPerDay length: 18 -> urlsPerDay length: 21 -> urlsPerDay length: 24 -> urlsPerDay ...
Apache-2.0
resources/notebooks/OldScrapper/ElPais-getUrlsFromHemeroteca.ipynb
cfespinoza/comments-retriever
Getting urls
url="https://www.elpais.com/" renderUrl = render(url) renderedPage = htmlRenderer.fromstring(renderUrl) auxLinks = renderedPage.xpath("//a/@href") # obtener links, cuidado que alguno ya empieza por http... auxFinalLinks = list(dict.fromkeys([link for link in auxLinks if not link.end...
_____no_output_____
Apache-2.0
resources/notebooks/OldScrapper/ElPais-getUrlsFromHemeroteca.ipynb
cfespinoza/comments-retriever
!pip install geopandas # Read in solar image # Import library functions to download and read images import requests from io import BytesIO # Dataset: Distributed Solar Photovoltaic Array Location and Extent Data Set for Remote Sensing Object Identification # California Aerial Imagery SolarArrayPolygons.geojson url...
_____no_output_____
MIT
ShowSolarArrayLocations.ipynb
ccai-course/Module2-Mitigation
Wasserstein 1D with PyTorchIn this small example, we consider the following minization problem:\begin{align}\mu^* = \min_\mu W(\mu,\nu)\end{align}where $\nu$ is a reference 1D measure. The problem is handledby a projected gradient descent method, where the gradient is computedby pyTorch automatic differentiation. The ...
# Author: Nicolas Courty <ncourty@irisa.fr> # Rémi Flamary <remi.flamary@polytechnique.edu> # # License: MIT License import numpy as np import matplotlib.pylab as pl import matplotlib as mpl import torch from ot.lp import wasserstein_1d from ot.datasets import make_1D_gauss as gauss from ot.utils import proj_...
_____no_output_____
MIT
master/_downloads/cc2d1e2d3ec6e3b42bceea0b50c4db77/plot_wass1d_torch.ipynb
PythonOT/pythonot.github.io
Wasserstein barycenterIn this example, we consider the following Wasserstein barycenter problem$$ \\eta^* = \\min_\\eta\;\;\; (1-t)W(\\mu,\\eta) + tW(\\eta,\\nu)$$where $\\mu$ and $\\nu$ are reference 1D measures, and $t$is a parameter $\in [0,1]$. The problem is handled by a project gradientdescent method, where the ...
device = "cuda" if torch.cuda.is_available() else "cpu" # use pyTorch for our data x_torch = torch.tensor(x).to(device=device) a_torch = torch.tensor(a).to(device=device) b_torch = torch.tensor(b).to(device=device) bary_torch = torch.tensor((a + b).copy() / 2).to(device=device).requires_grad_(True) lr = 1e-6 nb_iter...
_____no_output_____
MIT
master/_downloads/cc2d1e2d3ec6e3b42bceea0b50c4db77/plot_wass1d_torch.ipynb
PythonOT/pythonot.github.io
Remove empty folders
import shutil from os import listdir for repo in hw4: try: l = listdir(repo.name) except FileNotFoundError: pass if len(l) < 2: # has .git folder shutil.rmtree(repo.name)
_____no_output_____
CC0-1.0
Download_Repos.ipynb
rajathkmp/COMS4995-s18
Convert notebooks to python files
from glob import glob notebooks = glob("*/*.ipynb") import nbconvert import shlex for notebook in tqdm.tqdm(notebooks): #print(notebook) # fixme: whitespace in names? if not os.path.exists(notebook.replace("ipynb", "py")): os.system("jupyter-nbconvert {} --to script".format(shlex.quote(notebook)))...
Report Url: http://moss.stanford.edu/results/374137986
CC0-1.0
Download_Repos.ipynb
rajathkmp/COMS4995-s18
http://moss.stanford.edu/results/374137986
# Save report file m.saveWebPage(url, "report2.html") # Download whole report locally including code diff links mosspy.download_report(url, "submission2/", connections=8, log_level=20) import logging logging.DEBUG logging.WARNING # TODO: use absolute paths everywhere... def clone_repos(pattern="homework-1", store_at="...
_____no_output_____
CC0-1.0
Download_Repos.ipynb
rajathkmp/COMS4995-s18
Tidy Data with Pandas
# Reading the csv files into a pandas data frame temperature = pd.read_csv("../../datasets/temperature.csv") humidity = pd.read_csv("../../datasets/humidity.csv") wind_speed = pd.read_csv("../../datasets/wind_speed.csv") temperature.head() # Importing the libraries import pandas as pd import numpy as np# Displaying ...
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Data ManipulationLet us unpivot, or melt: convert from wide format to long format, as tidy-data thinking recommends.Tidy data essentially says: - Each row should be an observation - Each column should be a variable. Roughly, each column that is not an identifier or dimension should be a measure. - A dataframe...
tidy_temperature = pd.melt(temperature, id_vars="datetime", var_name="city", value_name="temperature") tidy_temperature.describe(include='all') tidy_temperature.head() tidy_temperature.sample(20) tidy_humidity = pd.melt(humidity, id_var...
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Let's cleanup the data There are many strategies to deal with NaN data. Here, since it is weather, perhaps a reasonable way would be interpolating the temperature, humidity and wind_speed. In other words, the tempeture today is reasonable between that of yesterday and tomorrow, as a good approximation.
raw_weather.describe() # The amount of missing values raw_weather.isna().sum() weather = raw_weather.interpolate() weather.isna().sum()
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
This is because we could not interpolate into the first row! Therefore, let us omit it.
weather = weather.dropna() weather.isna().sum() # Filter down to only San Francisco weather sf_weather = weather[weather['city'] == 'San Francisco'] sf_weather.sample(10) # Project down to only temperature and humidity data = weather[['datetime', 'city','temperature', 'humidity']] data.sample(10) # The average weather ...
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Note the two-levels of the columns above. Let us now flatten the data:
means = means.reset_index() means.head()
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Now, let's join it back with the original data
means.sample(10) df = means.set_index('city')
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Therefore, now we can remove the unnecessary column city.
means_data = means.drop(['city'], axis=1) means_data.sample(10) cor = means_data.corr() cor data = weather.merge(means, left_on='city', right_on='city') data.sample(10)
_____no_output_____
MIT
notebook/python/tidy-data-with-pandas.ipynb
praveenhm/machine-learning-tutorials
Germany: LK Wesermarsch (Niedersachsen)* Homepage of project: https://oscovida.github.io* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Wesermarsch.ipynb)
import datetime import time start = datetime.datetime.now() print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}") %config InlineBackend.figure_formats = ['svg'] from oscovida import * overview(country="Germany", subregion="LK Wesermarsch"); # load the data cases, deaths, ...
_____no_output_____
CC-BY-4.0
ipynb/Germany-Niedersachsen-LK-Wesermarsch.ipynb
RobertRosca/oscovida.github.io
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Germany-Niedersachsen-LK-Wesermarsch.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyte...
print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and " f"deaths at {fetch_deaths_last_execution()}.") # to force a fresh download of data, run "clear_cache()" print(f"Notebook execution took: {datetime.datetime.now()-start}")
_____no_output_____
CC-BY-4.0
ipynb/Germany-Niedersachsen-LK-Wesermarsch.ipynb
RobertRosca/oscovida.github.io
Центр непрерывного образования Программа «Python для автоматизации и анализа данных»Неделя 3 - 1*Ян Пиле, НИУ ВШЭ* Цикл for. Применение циклов к строкам, спискам, кортежам и словарям. Циклы мы используем в тех случаях, когда нужно повторить что-нибудь n-ное количество раз. Например, у нас уже был цикл **While**
ss = {1,2,3} ss.pop() ss.pop() i = 1 while i<=10: print(i) i+=1
1 2 3 4 5 6 7 8 9 10
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Здесь мы проверяем условие *i <= 10* (оно выполнено, *i = 1*), заходим в цикл с *i = 1*, печатаем значение *i*, добавляем к нему 1 иииии... \Снова проверяем условие *i <= 10* (оно выполнено, *i = 2*), заходим в цикл с *i = 2*, печатаем значение *i*, добавляем к нему 1 иииии... \Делаем такие же действия, пока *i* не ста...
i = 1 while True: print(i) i+=1 if i==11: break
1 2 3 4 5 6 7 8 9 10
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
FOR В Python цикл начинается с ключевого слова **for**, за которым следует произвольное имя переменной, которое будет хранить значения следующего объекта последовательности. Общий синтаксис **for...in** в python выглядит следующим образом:**for** **in** : **else:** Элементы “последовательности” перебир...
languages = ["C", "C++", "Perl", "Python"] for x in languages: print(x)
C C++ Perl Python
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Элементы “последовательности” перебираются один за другим “переменной” цикла; \если быть точным, переменная указывает на элементы. Для каждого элемента выполняется “действие”.\Здесь в роли "последовательности" у нас список Итерируемый объект **Итерация** - это общий термин, который описывает процедуру взятия элементов...
s = {1,2,3,4,5} print(type(s)) print(type(iter(s))) for i in iter(s): print(i)
1 2 3 4 5
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Посмотрим на встроенную функцию next(). Она должна отдавать следующий элемент итератора.
s = {1,2,3,4,5} s_iter = iter(s) print(next(s_iter)) print(next(s_iter)) print(next(s_iter))
1 2 3
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Отлично! мы по одному научились перебирать элементы из итерируемого объекта. Стоит отдельно остановиться на том, что цикл **for**, в Python, устроен несколько иначе, чем в большинстве других языков. Он больше похож на **for...each**, или же **for...of**. Например, для Javascript проход по списку с выводом на печать все...
%%js let numbers = [10, 12, 15, 18, 20]; for (let i = 0; i < numbers.length; i += 1) { console.log(numbers[i]) } l = [1,2,3,4,5] list(map(str,l))
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Если же, мы перепишем цикл **for** с помощью цикла **while**, используя индексы, то работать такой подход будет только с последовательностями:
list_of_numbers = [1,2,3] index = 0 while index < len(list_of_numbers): print(list_of_numbers[index]) index += 1
1 2 3
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
А с итерируемыми объектами, последовательностями не являющимися, не будет (потому что в множестве к элементу по индексу не обращаются!):
set_of_numbers = {1,2,3} index = 0 while index < len(set_of_numbers): print(set_of_numbers[index]) index += 1
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Ну если уж прям совсем никак без индексации, то к любому итерируемому объекту можно применить функцию enumerate(), \которая, как следует из названия, коллекцию занумерует. Здесь мы наделали кортежей вида (индекс, элемент)
set_of_numbers = {1,2,3,4,5,6} for i in enumerate(set_of_numbers): print(i)
(0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6)
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Чтобы выдавать это в человеческом виде, можно прямо после for сказать, что мы "итерируемся" по индексам и объектам. \Выглядит это следующим образом:
set_of_numbers = [1,2,3] for index, element in enumerate(set_of_numbers): print(index, element)
0 1 1 2 2 3
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Немного умных слов об итераторах**Протокол итератора**Теперь формализуем протокол итератора целиком:* Чтобы получить итератор мы должны передать функции iter итерируемый объект.* Далее мы передаём итератор функции next.* Когда элементы в итераторе закончились, порождается исключение StopIteration. (Пока представим себ...
x = 'Take a look around' for i in x: print(i) # Здесь мы прошлись по элементам списка и посчитали их сумму # В цикл вошли с total = 0 и на каждом элементе добавляли к total значение элемента x = [1,2,3,4] total = 0 for i in x: total+=i print(total) # Здесь мы прошлись по элементам кортежа и посчитали сумму тех...
34 {1, 2, 3, 4, 7, 49, 23, 28, 63}
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
СловариВ случае словарей итерация (по умолчанию) происходит по ключам
d = {'foo': 1, 'bar': 2, 'baz': 3} for k in d: print(k)
foo bar baz
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Но по ключам можно вынимать и соответствующие значения
for k in d: print(d[k])
1 2 3
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Также можно напрямую указать, по чему мы итерируемся: по ключам, по значениям или по кортежам ключ-значение\Помните методы **.values()** , **.keys()** и **.items()** ?
print(d) for v in d.values(): print(v) print(d) for v in d.keys(): print(v) print(d) for v in d.items(): print(v)
{'foo': 1, 'bar': 2, 'baz': 3} ('foo', 1) ('bar', 2) ('baz', 3)
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
А еще можно "распаковать" эти кортежи-ключ значения (примерно так же, как мы сделали для **enumerate**)
d = {'foo': 1, 'bar': 2, 'baz': 3} for k, v in d.items(): print('k =', k, ', v =', v)
k = foo , v = 1 k = bar , v = 2 k = baz , v = 3
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Перед тем, как начать решать какие-то задачи, остается упомянуть крайне полезную функцию **range()**. \Простыми словами, **range()** позволяет вам генерировать ряд чисел в рамках заданного диапазона. В зависимости от того, как много аргументов вы передаете функции, вы можете решить, где этот ряд чисел начнется и законч...
# Это как раз первый случай (мы вывели все целые числа ДО трех) for i in range(3): print(i) # Это второй случай (мы вывели все целые числа от 0 до 10 не включая правый конец) for i in range(0, 10): print(i) # Ну а это третий случай (мы вывели все целые числа от 0 до 10 не включая правый конец с шагом 2) # То ес...
0 2 4 6 8
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Шаг здесь может быть положительным или отрицательным числом, но не может быть нулем! Отрицательное число будет означать уменьшение аргумента, то есть:
for i in range(10, 0, -1): print(i)
10 9 8 7 6 5 4 3 2 1
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
А теперь отличие от итераторов! У range можно обратиться к элементу или даже срезу (как в списках)
print(range(3)[1]) print(range(10)[2:5])
range(2, 5)
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Немного истории: в Python 2 были функции **range** и **xrange**. Первая создавала список (прям настоящий список), а вторая - \именно то, что теперь в Python 3 называется **range** Задача 1Считайте с клавиатуры несколько чисел через пробел и выведите сумму их кубов**Вход:** 1 2 3 \**Выход:** 36
# Решение numbers = map(int,input().split()) x = 0 for i in numbers: x += i**2 print(x)
1 2 3 4 5 6 91
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Задача 2Считайте с клавиатуры две последовательности чисел через пробел и выведите список уникальных общих элементов этих двух последовательностей. Сделать это можно с помощью вложенного цикла for и, например, множеств.**Вход:** Последовательность 1: 1 2 3 Последовательность 2: 2,2,4,7,...
common = set() list1 = list(map(int,input().split())) list2 = list(map(int,input().split())) for elem1 in list1: for elem2 in list2: if elem1 == elem2: common.add(elem1) break print(common)
1 2 3 4 5 2 2 3 3 {2, 3}
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Но можно было и без этого. Решать можно было в несколько строк с использованием функционала множеств
set1 = set(map(int,input().split())) set2 = set(map(int,input().split())) set1.intersection(set2)
1 2 2 2 2 3 4 6 4 3 7 6 3 2
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Задача 3Дан список, содержащий строки, целые числа и числа с плавающей точкой. Разбить его на три списка так, чтобы в одном остались только строки, в другом - только целые числа, а в третьем - только числа с плавающей точкой. Заметьте, что при проверке типов название типа пишется без кавычек, например **int**.**Вход:*...
#Решение list1 = [1, 2, 5.6, 7.5, 'Boo', 1, 'RocknRoll'] ints, floats, strings = [], [], [] for i in list1: if type(i)==int: ints.append(i) elif type(i)==float: floats.append(i) else: strings.append(i) print(ints) print(floats) print(strings)
[1, 2, 1] [5.6, 7.5] ['Boo', 'RocknRoll']
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Генераторы списков и списковые включения. aka List ComprehensionsЭтот элемент языка считается его "визитной карточкой". Это своего рода метод быстро создать новый список, не применяя цикл for. Пусть мы, к примеру, хотим создать список с числами от 0 до 20
a = [] for i in range(20): a.append(i) a
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Это же выражение можно записать с помощью спискового включения
a = [i for i in range(20)] print(type(a)) print(a)
<class 'list'> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Что мы видим? Во-первых, на выходе такой конструкцими мы получили лист (конечно, это же СПИСКОВОЕ включение). А во-вторых, все написано в одну строчку и , кажется следует вот такой конструкции:**new_list** = [**expression** for **member** in **iterable**]1. **expression** какое либо вычисление, вызов метода или любое д...
lst = [1,2,3,4,5,45,67,8,765,854,76] x = [str(i) for i in lst] x
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Но и это еще не все. В списковое включение можно добавить какое нибудь условие (как мы это делали с **if**). Выглядеть это будет так: new_list = [expression for member in iterable (if conditional)]Разберем на примере:
lst = [1,2,3,4,5,45,67,8,765,854,76] x = [i for i in lst if i%2 == 0] #Здесь я взял и включил в новый список только четные элементы x
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Более того - не зря в условии написано iterable, а не list. Значит можно попробовать проделать что-то подобное с любыми другими итерируемыми объектами. с кортежами все точно должно получиться:
# Предложение sentence = '''The rocket, who was named Ted, came back from Mars because he missed his friends.''' # Гласные английского языка и пробел vowels = 'aeiou ' # достанем в список все символы строки, которые не являются гласными и пробелом. consonants = [i for i in sentence if i not in vowels] c...
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
А еще вот так можно было... Не зря же регулярные выражения проходили.
import re re.findall(r'[^aeiou ]',sentence)
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Мы уже поняли, что можно поместить условие в конец оператора для простой фильтрации, но что, если хочется изменить значение элемента вместо его фильтрации? В этом случае полезно поместить условное выражение в начале выражения. Выглядит это вот так: new_list = [expression (if conditional) for member in iterable]С пом...
original_prices = [1.25, -9.45, 10.22, 3.78, -5.92, 1.16] prices = [i if i > 0 else 0 for i in original_prices] prices
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Здесь, наше выражение **i** содержит условный оператор, **if i> 0** else **0**. Это говорит Python выводить значение **i**, если число положительное, но менять **i** на **0**, если число отрицательное. Включения для множеств и словарей Хотя **list comprehension** в Python является распространенным инструментом, вы так...
quote = "life, uh, finds a way" unique_vowels = {i for i in quote if i in 'aeiou'} unique_vowels
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Здесь мы вывели все уникальные гласные, которые встретились в строке **Dictionary comprehensions** , по сути, работает так же, но с дополнительным требованием определения ключа. Ключ отделяется двоеточием.
squares = {i: i * i for i in range(10)} squares
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Генераторы списков По сути, это то же самое, что списковое включение, но только возвращает оно не сам список, а генератор.
type((i * i for i in range(10)))
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Проверим:
x = (i * i for i in range(10)) next(x) next(x)
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Так-так, функция next работает.
x[4]
_____no_output_____
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
К элементам обращаться нельзя
x = (i * i for i in range(10)) while True: print(next(x))
0 1 4 9 16 25 36 49 64 81
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
**StopIteration!** Опять что-то знакомое) Получается, что генератор, это , на самом деле, какой-то вид итератора. Так оно и есть. Генератор это итератор, который можно получить с помощью генераторного выражения, например, (i * i for i in range(10)) или с помощью функции-генератора (но об этом в следующей серии. Так а з...
%time sum([i * i for i in range(1000000)]) %time sum(i * i for i in range(1000000))
CPU times: user 2 µs, sys: 0 ns, total: 2 µs Wall time: 3.81 µs
MIT
lect04_for/.ipynb_checkpoints/for-checkpoint.ipynb
pileyan/DPO_python_2022
Class 14: Prescott's Real Business Cycle Model IIn this notebook, we'll consider a centralized version of the model from pages 11-17 in Edward Prescott's article "Theory Ahead of Business Cycle Measurement in the Fall 1986 of the Federal Reserve Bank of Minneapolis' *Quarterly Review* (link to article: https://www.min...
# Create a variable called 'parameters' that stores the model parameter values in a Pandas Series parameters = pd.Series(dtype=float) parameters['rho'] = .75 parameters['beta'] = 0.99 parameters['phi'] = 1.7317 parameters['alpha'] = 0.35 parameters['delta'] = 0.025 # Print the model's parameters print(parameters) # Cr...
_____no_output_____
MIT
Lecture Notebooks/Econ126_Class_14.ipynb
letsgoexploring/econ126
Next, initialize the model using `ls.model` which takes the following required arguments:* `equations`* `n_states`* `var_names`* `shock_names`* `parameters`
# Initialize the model into a variable named 'rbc_model' rbc_model = ls.model(equations = equilibrium_equations, n_states=2, var_names=var_names, shock_names=shock_names, parameters=parameters) # Compute the steady state numerically using .compute_ss()...
_____no_output_____
MIT
Lecture Notebooks/Econ126_Class_14.ipynb
letsgoexploring/econ126
Impulse ResponsesCompute a 26 period impulse responses of the model's variables to a 0.01 unit shock to TFP in period 5.
# Compute impulse responses rbc_model.impulse(T=26,t0=5,shocks=[0.01,0]) # Print the first 10 rows of the computed impulse responses to the TFP shock print(rbc_model.irs['e_a'].head(10))
e_a a k y c i l 0 0.00 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 1 0.00 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 2 0.00 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 3 0.00 0.000000 0.000000 0.000000 0.000000 ...
MIT
Lecture Notebooks/Econ126_Class_14.ipynb
letsgoexploring/econ126
Construct a $2\times3$ grid of plots of simulated TFP, output, labor, consumption, investment, and capital. Be sure to multiply simulated values by 100 so that vertical axis units are in "percent deviation from steady state."
# Create figure. PROVIDED fig = plt.figure(figsize=(18,8)) # Create upper-left axis. PROVIDED ax = fig.add_subplot(2,3,1) ax.plot(rbc_model.irs['e_a']['a']*100,'b',lw=5,alpha=0.75) ax.set_title('TFP') ax.set_ylabel('% dev from steady state') ax.set_ylim([-0.5,2]) ax.grid() # Create upper-center axis. PROVIDED ax = fi...
_____no_output_____
MIT
Lecture Notebooks/Econ126_Class_14.ipynb
letsgoexploring/econ126
The thermodynamics of ideal solutions*Authors: Enze Chen (University of California, Berkeley)*This animation will show how the Gibbs free energy curves correspond to a lens phase diagram. Python imports
# General libraries import io import os # Scientific computing libraries import numpy as np from scipy.misc import derivative import matplotlib import matplotlib.pyplot as plt %matplotlib inline import matplotlib.animation as animation from PIL import Image import cv2 from moviepy.editor import *
_____no_output_____
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Helper functions
# analytical function for the solid free energy curve def curve_s(x, T, beta=0): """This function plots the Gibbs free energy curve for the solid solution. Args: x (numpy.ndarray): An array of atomic fractions of B. T (float): The temperature in Kelvin. beta (float): The interaction...
_____no_output_____
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Animations using `FuncAnimation`Finally!! VLC/Windows has buggy glitches, but the embedded HTML version looks fine.Also, **extremely high quality and low memory footprint**!! 🎉
# Initialize quantities n = int(1e4) xmin, xmax = (0.001, 0.999) x = np.linspace(xmin, xmax, n) liquidus = [] solidus = [] Ts = np.arange(1300, 2301, 5) # Plot settings plt.rcParams.update({'figure.figsize':(7,9.5), 'font.size':16}) fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True) # Initialize plot settings ymin...
1300 1400 1500 1600 1700 1800 1900 2000 2100 2200 2300
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Other (sub-par) methods that I've tried...
# Accumulate images in a list for post-processing n = int(1e4) xmin, xmax = (0.001, 0.999) x = np.linspace(xmin, xmax, n) liquidus = [] solidus = [] Ts = np.arange(1300, 1450, 10) plt.rcParams.update({'figure.figsize':(7,9)}) fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True) fig.tight_layout() ymin, ymax = -39, 19...
_____no_output_____
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Convert PIL images to mp4 using [OpenCV](https://docs.opencv.org/master/d6/d00/tutorial_py_root.html)OK, this works! Quality could be improved... this is where FuncAnimation native support would probably be better.
# This movie is very large in size!! opencv_images = [cv2.cvtColor(np.array(i), cv2.COLOR_RGB2BGR) for i in images] height, width, channels = opencv_images[0].shape fourcc = cv2.VideoWriter_fourcc(*'MP4V') # can also be 'MJPG' or 'MP4V' video = cv2.VideoWriter(filename='C:/Users/Enze/Desktop/test_opencv.mp4', ...
_____no_output_____
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Convert figure files using [`moviepy`](https://moviepy.readthedocs.io/en/latest/index.html)Quality seems a little worse than OpenCV. Also takes a longggg time lol, but the file size is very small!
datadir = 'C:/Users/Enze/Desktop/plots/' clips = [ImageClip(os.path.join(datadir, m)).set_duration(0.2) for m in os.listdir(datadir)] concat = concatenate_videoclips(clips, method='compose') concat.write_videofile('C:/Users/Enze/Desktop/test_moviepy.mp4', fps=10)
_____no_output_____
CC0-1.0
assets/fig/scripts/thermo_animation.ipynb
LuisG-R/mi-book
Character level language model - Dinosaurus IslandWelcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to giv...
import numpy as np from utils import * import random import pprint
_____no_output_____
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
1 - Problem Statement 1.1 - Dataset and PreprocessingRun the following cell to read the dataset of dinosaur names, create a list of unique characters (such as a-z), and compute the dataset and vocabulary size.
data = open('dinos.txt', 'r').read() data= data.lower() chars = list(set(data)) data_size, vocab_size = len(data), len(chars) print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
There are 19909 total characters and 27 unique characters in your data.
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
* The characters are a-z (26 characters) plus the "\n" (or newline character).* In this assignment, the newline character "\n" plays a role similar to the `` (or "End of sentence") token we had discussed in lecture. - Here, "\n" indicates the end of the dinosaur name rather than the end of a sentence. * `char_to_i...
chars = sorted(chars) print(chars) char_to_ix = { ch:i for i,ch in enumerate(chars) } ix_to_char = { i:ch for i,ch in enumerate(chars) } pp = pprint.PrettyPrinter(indent=4) pp.pprint(ix_to_char)
{ 0: '\n', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', ...
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
1.2 - Overview of the modelYour model will have the following structure: - Initialize parameters - Run the optimization loop - Forward propagation to compute the loss function - Backward propagation to compute the gradients with respect to the loss function - Clip the gradients to avoid exploding gradients ...
### GRADED FUNCTION: clip def clip(gradients, maxValue): ''' Clips the gradients' values between minimum and maximum. Arguments: gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby" maxValue -- everything above this number is set to this number, and everything...
gradients["dWaa"][1][2] = 10.0 gradients["dWax"][3][1] = -10.0 gradients["dWya"][1][2] = 0.29713815361 gradients["db"][4] = [ 10.] gradients["dby"][1] = [ 8.45833407]
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
** Expected output:**```Pythongradients["dWaa"][1][2] = 10.0gradients["dWax"][3][1] = -10.0gradients["dWya"][1][2] = 0.29713815361gradients["db"][4] = [ 10.]gradients["dby"][1] = [ 8.45833407]```
# Test with a maxValue of 5 mValue = 5 np.random.seed(3) dWax = np.random.randn(5,3)*10 dWaa = np.random.randn(5,5)*10 dWya = np.random.randn(2,5)*10 db = np.random.randn(5,1)*10 dby = np.random.randn(2,1)*10 gradients = {"dWax": dWax, "dWaa": dWaa, "dWya": dWya, "db": db, "dby": dby} gradients = clip(gradients, mValue...
gradients["dWaa"][1][2] = 5.0 gradients["dWax"][3][1] = -5.0 gradients["dWya"][1][2] = 0.29713815361 gradients["db"][4] = [ 5.] gradients["dby"][1] = [ 5.]
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
** Expected Output: **```Pythongradients["dWaa"][1][2] = 5.0gradients["dWax"][3][1] = -5.0gradients["dWya"][1][2] = 0.29713815361gradients["db"][4] = [ 5.]gradients["dby"][1] = [ 5.]``` 2.2 - SamplingNow assume that your model is trained. You would like to generate new text (characters). The process of generation is e...
matrix1 = np.array([[1,1],[2,2],[3,3]]) # (3,2) matrix2 = np.array([[0],[0],[0]]) # (3,1) vector1D = np.array([1,1]) # (2,) vector2D = np.array([[1],[1]]) # (2,1) print("matrix1 \n", matrix1,"\n") print("matrix2 \n", matrix2,"\n") print("vector1D \n", vector1D,"\n") print("vector2D \n", vector2D) print("Multiply 2D a...
Adding a (3,) vector to a (3 x 1) vector broadcasts the 1D array across the second dimension Not what we want here! [[2 4 6] [2 4 6] [2 4 6]]
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
- **Step 3**: Sampling: - Now that we have $y^{\langle t+1 \rangle}$, we want to select the next letter in the dinosaur name. If we select the most probable, the model will always generate the same result given a starting letter. To make the results more interesting, we will use np.random.choice to select a next le...
# GRADED FUNCTION: sample def sample(parameters, char_to_ix, seed): """ Sample a sequence of characters according to a sequence of probability distributions output of the RNN Arguments: parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b. char_to_ix -- python dictio...
Sampling: list of sampled indices: [12, 17, 24, 14, 13, 9, 10, 22, 24, 6, 13, 11, 12, 6, 21, 15, 21, 14, 3, 2, 1, 21, 18, 24, 7, 25, 6, 25, 18, 10, 16, 2, 3, 8, 15, 12, 11, 7, 1, 12, 10, 2, 7, 7, 11, 17, 24, 12, 13, 24, 0] list of sampled characters: ['l', 'q', 'x', 'n', 'm', 'i', 'j', 'v', 'x', 'f', 'm', 'k', 'l', '...
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
** Expected output:**```PythonSampling:list of sampled indices: [12, 17, 24, 14, 13, 9, 10, 22, 24, 6, 13, 11, 12, 6, 21, 15, 21, 14, 3, 2, 1, 21, 18, 24, 7, 25, 6, 25, 18, 10, 16, 2, 3, 8, 15, 12, 11, 7, 1, 12, 10, 2, 7, 7, 11, 17, 24, 12, 13, 24, 0]list of sampled characters: ['l', 'q', 'x', 'n', 'm', 'i', 'j', 'v', ...
# GRADED FUNCTION: optimize def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the...
Loss = 126.503975722 gradients["dWaa"][1][2] = 0.194709315347 np.argmax(gradients["dWax"]) = 93 gradients["dWya"][1][2] = -0.007773876032 gradients["db"][4] = [-0.06809825] gradients["dby"][1] = [ 0.01538192] a_last[4] = [-1.]
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
** Expected output:**```PythonLoss = 126.503975722gradients["dWaa"][1][2] = 0.194709315347np.argmax(gradients["dWax"]) = 93gradients["dWya"][1][2] = -0.007773876032gradients["db"][4] = [-0.06809825]gradients["dby"][1] = [ 0.01538192]a_last[4] = [-1.]``` 3.2 - Training the model * Given the dataset of dinosaur names, ...
# GRADED FUNCTION: model def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27, verbose = False): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character ...
_____no_output_____
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
Run the following cell, you should observe your model outputting random-looking characters at the first iteration. After a few thousand iterations, your model should learn to generate reasonable-looking names.
parameters = model(data, ix_to_char, char_to_ix, verbose = True)
j = 0 idx = 0 single_example = turiasaurus single_example_chars ['t', 'u', 'r', 'i', 'a', 's', 'a', 'u', 'r', 'u', 's'] single_example_ix [20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19] X = [None, 20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19] Y = [20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19, 0] Iteration: 0, Loss: 23.0...
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
** Expected Output**```Pythonj = 0 idx = 0single_example = turiasaurussingle_example_chars ['t', 'u', 'r', 'i', 'a', 's', 'a', 'u', 'r', 'u', 's']single_example_ix [20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19] X = [None, 20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19] Y = [20, 21, 18, 9, 1, 19, 1, 21, 18, 21, 19, 0] It...
from __future__ import print_function from keras.callbacks import LambdaCallback from keras.models import Model, load_model, Sequential from keras.layers import Dense, Activation, Dropout, Input, Masking from keras.layers import LSTM from keras.utils.data_utils import get_file from keras.preprocessing.sequence import p...
Using TensorFlow backend.
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
To save you some time, we have already trained a model for ~1000 epochs on a collection of Shakespearian poems called [*"The Sonnets"*](shakespeare.txt). Let's train the model for one more epoch. When it finishes training for an epoch---this will also take a few minutes---you can run `generate_output`, which will prom...
print_callback = LambdaCallback(on_epoch_end=on_epoch_end) model.fit(x, y, batch_size=128, epochs=1, callbacks=[print_callback]) # Run this cell to try with different inputs without having to re-train the model generate_output()
_____no_output_____
MIT
notebooks/Dinosaurus_Island_Character_level_language_model_final_v3b.ipynb
tfburns/deep-learning-specialization
Central Limit Theorem - Part IIWork through the questions and use the created variables to answer the questions that follow below the notebook.Run the below cell to get started.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline np.random.seed(42) pop_data = np.random.gamma(1,100,3000) plt.hist(pop_data);
_____no_output_____
MIT
Part 3 Descriptive Statistics/Study materials/08-sampling-distributions/08_Sampling Distributions/Sampling Distributions - 19 - Central Limit Theorem - Part II.ipynb
bimarsha7/Data-analysis
`1.` In order to create the sampling distribution for the average of 100 draws of this distribution, follow these steps:`a.` Use numpy's **random.choice** to simulate 100 draws from the `pop_data` array. `b.` Compute the mean of these 100 draws. `c.` Write a loop to simulate this process 10,000 times, and store each ...
means_size_100 = [] for _ in range(10000): sample = np.random.choice(pop_data, 100) means_size_100.append(sample.mean()) plt.hist(means_size_100);
_____no_output_____
MIT
Part 3 Descriptive Statistics/Study materials/08-sampling-distributions/08_Sampling Distributions/Sampling Distributions - 19 - Central Limit Theorem - Part II.ipynb
bimarsha7/Data-analysis
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Classification on imbalanced data View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This tutorial demonstrates how to classify a highly imbalanced dataset in which the number of examples in one class greatly outnumbers the examples in another. You will work...
import tensorflow as tf from tensorflow import keras import os import tempfile import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import sklearn from sklearn.metrics import confusion_matrix from sklearn.model_selection import train_test_split from sk...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Data processing and exploration Download the Kaggle Credit Card Fraud data setPandas is a Python library with many helpful utilities for loading and working with structured data. It can be used to download CSVs into a Pandas [DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.htmlpandas.DataFram...
file = tf.keras.utils raw_df = pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/creditcard.csv') raw_df.head() raw_df[['Time', 'V1', 'V2', 'V3', 'V4', 'V5', 'V26', 'V27', 'V28', 'Amount', 'Class']].describe()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Examine the class label imbalanceLet's look at the dataset imbalance:
neg, pos = np.bincount(raw_df['Class']) total = neg + pos print('Examples:\n Total: {}\n Positive: {} ({:.2f}% of total)\n'.format( total, pos, 100 * pos / total))
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
This shows the small fraction of positive samples. Clean, split and normalize the dataThe raw data has a few issues. First the `Time` and `Amount` columns are too variable to use directly. Drop the `Time` column (since it's not clear what it means) and take the log of the `Amount` column to reduce its range.
cleaned_df = raw_df.copy() # You don't want the `Time` column. cleaned_df.pop('Time') # The `Amount` column covers a huge range. Convert to log-space. eps = 0.001 # 0 => 0.1¢ cleaned_df['Log Ammount'] = np.log(cleaned_df.pop('Amount')+eps)
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Split the dataset into train, validation, and test sets. The validation set is used during the model fitting to evaluate the loss and any metrics, however the model is not fit with this data. The test set is completely unused during the training phase and is only used at the end to evaluate how well the model generaliz...
# Use a utility from sklearn to split and shuffle your dataset. train_df, test_df = train_test_split(cleaned_df, test_size=0.2) train_df, val_df = train_test_split(train_df, test_size=0.2) # Form np arrays of labels and features. train_labels = np.array(train_df.pop('Class')) bool_train_labels = train_labels != 0 val_...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Normalize the input features using the sklearn StandardScaler.This will set the mean to 0 and standard deviation to 1.Note: The `StandardScaler` is only fit using the `train_features` to be sure the model is not peeking at the validation or test sets.
scaler = StandardScaler() train_features = scaler.fit_transform(train_features) val_features = scaler.transform(val_features) test_features = scaler.transform(test_features) train_features = np.clip(train_features, -5, 5) val_features = np.clip(val_features, -5, 5) test_features = np.clip(test_features, -5, 5) prin...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Caution: If you want to deploy a model, it's critical that you preserve the preprocessing calculations. The easiest way to implement them as layers, and attach them to your model before export. Look at the data distributionNext compare the distributions of the positive and negative examples over a few features. Good q...
pos_df = pd.DataFrame(train_features[ bool_train_labels], columns=train_df.columns) neg_df = pd.DataFrame(train_features[~bool_train_labels], columns=train_df.columns) sns.jointplot(pos_df['V5'], pos_df['V6'], kind='hex', xlim=(-5,5), ylim=(-5,5)) plt.suptitle("Positive distribution") sns.jointplot(neg_...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Define the model and metricsDefine a function that creates a simple neural network with a densly connected hidden layer, a [dropout](https://developers.google.com/machine-learning/glossary/dropout_regularization) layer to reduce overfitting, and an output sigmoid layer that returns the probability of a transaction bei...
METRICS = [ keras.metrics.TruePositives(name='tp'), keras.metrics.FalsePositives(name='fp'), keras.metrics.TrueNegatives(name='tn'), keras.metrics.FalseNegatives(name='fn'), keras.metrics.BinaryAccuracy(name='accuracy'), keras.metrics.Precision(name='precision'), keras.metrics...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Understanding useful metricsNotice that there are a few metrics defined above that can be computed by the model that will be helpful when evaluating the performance.* **False** negatives and **false** positives are samples that were **incorrectly** classified* **True** negatives and **true** positives are samples ...
EPOCHS = 100 BATCH_SIZE = 2048 early_stopping = tf.keras.callbacks.EarlyStopping( monitor='val_prc', verbose=1, patience=10, mode='max', restore_best_weights=True) model = make_model() model.summary()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Test run the model:
model.predict(train_features[:10])
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs
Optional: Set the correct initial bias. These initial guesses are not great. You know the dataset is imbalanced. Set the output layer's bias to reflect that (See: [A Recipe for Training Neural Networks: "init well"](http://karpathy.github.io/2019/04/25/recipe/2-set-up-the-end-to-end-trainingevaluation-skeleton--get-du...
results = model.evaluate(train_features, train_labels, batch_size=BATCH_SIZE, verbose=0) print("Loss: {:0.4f}".format(results[0]))
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/imbalanced_data.ipynb
arshPratap/docs