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 |
|---|---|---|---|---|---|
Next, let's import the function "kappa_in" located in the file kappa_calculation.py. This function calculates the photon loss of a CPW resonator which is capacitively coupled to an input transmission line. | # Import the function "kappa_in" from the file kappa_calculation.py
from qiskit_metal.analyses.em.kappa_calculation import kappa_in | _____no_output_____ | Apache-2.0 | tutorials/6 Analysis/CPW_kappa_calculation_demo.ipynb | mtreinish/qiskit-metal |
The function "kappa_in" takes either three or six arguments, depending on how the lowest resonant frequency of the resonator is handled. In the first case, the resonant frequency of the CPW resonator is calculated numerically (using HFSS, for example) and passed as in floating-point input along with the frequency of in... | # SANITY CHECK #1
# Let's check that output is only given for three and six arguments
print("Output for N=1 Arguments:", kappa_in(1.0))
print("Output for N=2 Arguments:", kappa_in(1.0, 1.0))
print("Output for N=3 Arguments:", kappa_in(1.0, 1.0, 1.0))
print("Output for N=4 Arguments:", kappa_in(1.0, 1.0, 1.0, 1.0))
p... | Output for N=1 Arguments: None
Output for N=2 Arguments: None
Output for N=3 Arguments: 1591.5494309189535
Output for N=4 Arguments: None
Output for N=5 Arguments: None
Output for N=6 Arguments: 3234.721973158391
Output for N=7 Arguments: None
| Apache-2.0 | tutorials/6 Analysis/CPW_kappa_calculation_demo.ipynb | mtreinish/qiskit-metal |
Now, let's actually calculate the photon loss for a representative CPW resonator with realistic values of input parameters. Here we'll assume a qubit frequency of 5 GHz, capacitive coupling of 30fF and a CPW resonant frequency of 4 GHz. The calculated value of kappa is the range of 0-1 MHz, as expected. | # SANITY CHECK #2
# Let's check that the magnitude of the output is what we would expect for 3 arguments:
# Input #1: omega = 5GHz = 5E9 Hertz
# Input #2: C_in = 30fF = 30E-15 Farads
# Input #3: omega_n = 4GHz = 4.5E9 Hertz
print("Calculated kappa (in Hz):", kappa_in(5.0E9, 30.0E-15, 4.5E9), "Hz")
print("Calculated ... | Calculated kappa (in Hz): 161144.37988054403 Hz
Calculated kappa (in MHz): 0.16114437988054403 MHz
| Apache-2.0 | tutorials/6 Analysis/CPW_kappa_calculation_demo.ipynb | mtreinish/qiskit-metal |
Comparing various online solversAn example showing how different online solvers performon the hand-written digits dataset. | # Author: Rob Zinkov <rob at zinkov dot com>
# License: BSD 3 clause
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import SGDClassifier, Perceptron
from sklearn.linear_model import PassiveAggressiveClassif... | _____no_output_____ | MIT | sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_sgd_comparison.ipynb | wangyendt/deeplearning_models |
Try Different base models. | logreg = LogisticRegression()
logreg_cv = LogisticRegressionCV()
rf = RandomForestClassifier()
gboost = GradientBoostingClassifier()
models = [logreg, logreg_cv, rf, gboost]
for model in models:
print('Cross-validation of : {0}'.format(model.__class__))
score = compute_score(clf=model, X=train_reduced, y=targ... | _____no_output_____ | MIT | titanic/titanic_2.ipynb | utshabkg/ML_Web_Apps |
Save and Load Model | import pickle
import joblib
file = 'titanic.pkl'
joblib.dump(model, file)
load = joblib.load('titanic.pkl')
y_pred = load.predict(test).astype(int)
y_pred
val = pd.DataFrame(y_pred, columns = ['Survived'])
val = val.replace({1: 'Alive', 0: 'Died'})
val | _____no_output_____ | MIT | titanic/titanic_2.ipynb | utshabkg/ML_Web_Apps |
Notebook Goal & Approach GoalFor each FERC 714 respondent that reports hourly demand as an electricity planning area, create a geometry representing the geographic area in which that electricity demand originated. Create a separate geometry for each year in which data is available. Approach* Use the `eia_code` found... | %load_ext autoreload
%autoreload 2
# Standard Libraries:
import dateutil
import logging
import pathlib
import pickle
import re
import sys
import zipfile
# 3rd Party Libraries:
import contextily as ctx
import geopandas
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
impor... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Configure Output Formatting | sns.set()
%matplotlib inline
mpl.rcParams['figure.figsize'] = (20,8)
mpl.rcParams['figure.dpi'] = 150
pd.options.display.max_columns = 100
pd.options.display.max_rows = 100 | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Logging | logger = logging.getLogger()
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(stream=sys.stdout)
log_format = '%(asctime)s [%(levelname)8s] %(name)s:%(lineno)s %(message)s'
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)
logger.handlers = [handler] | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
PUDL Setup | pudl_settings = pudl.workspace.setup.get_defaults()
ferc1_engine = sa.create_engine(pudl_settings['ferc1_db'])
pudl_engine = sa.create_engine(pudl_settings['pudl_db'])
pudl_out = pudl.output.pudltabl.PudlTabl(pudl_engine)
pudl_settings | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Parameters | MAP_CRS = "EPSG:3857"
CALC_CRS = "ESRI:102003" | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Function Definitions Dummy EIA 861 ETL | def test_etl_eia(eia_inputs, pudl_settings):
"""
This is a dummy function that runs the first part of the EIA ETL
process -- everything up until the entity harvesting begins. For
use in this notebook only.
"""
eia860_tables = eia_inputs["eia860_tables"]
eia860_years = eia_inputs["eia860_yea... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Dummy EIA 861 Harvesting* Used to separately test the EIA entity harvesting process with EIA 861* Doesn't yet work b/c 861 is structured differently than 860/923. | def test_harvest_eia(eia_transformed_dfs, eia860_years, eia861_years, eia923_years):
entities_dfs, eia_transformed_dfs = pudl.transform.eia.transform(
eia_transformed_dfs,
eia860_years=eia860_years,
eia861_years=eia861_years,
eia923_years=eia923_years,
)
# convert types..
... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Compare Annual Demand vs. Sales | def annual_demand_vs_sales(dhpa_ferc714, sales_eia861, ba_eia861):
"""
Categorize EIA Codes in FERC 714 as BA or Utility IDs.
Most FERC 714 respondent IDs are associated with an `eia_code` which
refers to either a `balancing_authority_id_eia` or a `utility_id_eia`
but no indication is given as ... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
EIA Code Categorization | def categorize_eia_code(rids_ferc714, utils_eia860, ba_eia861):
"""
Categorize EIA Codes in FERC 714 as BA or Utility IDs.
Most FERC 714 respondent IDs are associated with an `eia_code` which
refers to either a `balancing_authority_id_eia` or a `utility_id_eia`
but no indication is given as to ... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Georeference Balancing Authorities | def georef_bas(ba_eia861, st_eia861, sales_eia861, census_gdf):
"""
Create a GeoDataFrame mapping BAs to Utils to county geometries by year.
This GDF includes the following columns:
balancing_authority_id_eia (ba_eia861)
balancing_authority_name_eia (ba_eia861)
balancing_authority_code... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Map Balancing Authorities | def map_ba(ba_ids, year, ba_util_county_gdf, save=False):
"""
Create a map of a balancing authority for a historical year.
Args:
ba_ids (iterable): A collection of Balancing Authority IDs.
year (int): The year for which to create a map.
ba_util_county_gdf (geopandas.GeoDataFrame... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Read Data EIA 860 via PUDL Outputs | plants_eia860 = pudl_out.plants_eia860()
utils_eia860 = pudl_out.utils_eia860() | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
EIA 861 (2010-2018)* Not yet fully integrated into PUDL* Post-transform harvesting process isn't compatible w/ EIA 861 structure* Only getting the `sales_eia861`, `balancing_authority_eia861`, and `service_territory_eia861` tables | %%time
logger.setLevel("WARN")
eia_years = list(range(2010, 2019))
eia_inputs = {
"eia860_years": [],
"eia860_tables": pudl.constants.pudl_tables["eia860"],
"eia861_years": eia_years,
"eia861_tables": pudl.constants.pudl_tables["eia861"],
"eia923_years": [],
"eia923_tables": pudl.constants.pudl_... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
FERC 714 (2006-2018) | %%time
logger.setLevel("WARN")
raw_ferc714 = pudl.extract.ferc714.extract(pudl_settings=pudl_settings)
tfr_ferc714 = pudl.transform.ferc714.transform(raw_ferc714)
logger.setLevel("INFO") | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
HIFLD Electricity Planning Areas (2018)* Electricty Planning Area geometries from HIFLD.* Indexed by `ID` which corresponds to EIA utility or balancing area IDs.* Only valid for 2017-2018. | hifld_pa_gdf = (
pudl.analysis.demand_mapping.get_hifld_planning_areas_gdf(pudl_settings)
.to_crs(MAP_CRS)
) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
US Census DP1 (2010)* This GeoDataFrame contains county-level geometries and demographic data. | %%time
census_gdf = (
pudl.analysis.demand_mapping.get_census2010_gdf(pudl_settings, layer="county")
.to_crs(MAP_CRS)
) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Combine Data Categorize FERC 714 Respondent IDs | rids_ferc714 = (
tfr_ferc714["respondent_id_ferc714"]
.pipe(categorize_eia_code, utils_eia860, ba_eia861)
) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Add FERC 714 IDs to HIFLD | hifld_pa_gdf = (
hifld_pa_gdf
.merge(rids_ferc714, left_on="ID", right_on="eia_code", how="left")
) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Add Respondent info to FERC 714 Demand | dhpa_ferc714 = pd.merge(
tfr_ferc714["demand_hourly_pa_ferc714"],
tfr_ferc714["respondent_id_ferc714"],
on="respondent_id_ferc714",
how="left", # There are respondents with no demand
) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Utilities vs. Balancing AuthoritiesExploration of the Balancing Authority EIA 861 table for cleanup Which columns are available in which years?| Year | BA ID | BA Name | BA Code | Util ID | Util Name | State | N ||------|-------|---------|---------|---------|-----------|-------|----|| 2010 | XXXXX | XXXXXXX | ... | # BA ID comes from EIA 861 BA Table
ba_ids = set(ba_eia861.balancing_authority_id_eia)
print(f"Total # of BA IDs: {len(ba_ids)}")
# Util ID comes from EIA 860 Utilities Entity table.
util_ids = set(pudl_out.utils_eia860().utility_id_eia)
print(f"Total # of Util IDs: {len(util_ids)}")
ba_not_util_ids = ba_ids.differen... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Missing IDs* There are `eia_code` values that don't show up in the list of balancing authority IDs (2010-2018).* There are also `eia_code` values that don't show up in the list of utility IDs (2009-2018).* There are a few `eia_code` values that don't show up in either!* Mostly this is an artifact of the different time... | rids_ferc714[
(~rids_ferc714.eia_code.isin(ba_eia861.balancing_authority_id_eia.unique())) &
(~rids_ferc714.eia_code.isin(utils_eia860.utility_id_eia.unique()))
]
rids_recent = (
dhpa_ferc714
.groupby(["respondent_id_ferc714", "report_year"])
.agg({"demand_mwh": sum})
.reset_index()
.query("... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
BA to Utility Mappings are Many to Many* Unsurprisingly, BAs often contain many utilities.* However, it's also common for utilities to participate in more than one BA.* About 1/3 of all utilities show up in association with more than one BA | ba_to_util_mapping = (
ba_eia861[["balancing_authority_id_eia", "utility_id_eia"]]
.dropna(subset=["balancing_authority_id_eia", "utility_id_eia"])
.drop_duplicates(subset=["balancing_authority_id_eia", "utility_id_eia"])
.groupby(["balancing_authority_id_eia"])
.agg({
"utility_id_eia": "cou... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Georeferenced Demand Fraction* With their original EIA codes the HIFLD Electricity Planning Areas only georeference some of the FERC 714 demand.* It's about 86% in 2018. In 2013 and earlier years, the fraction starts to drop off more quickly, to 76% in 2010, and 58% in 2006.* After manually identifying and fixing some... | annual_demand_ferc714 = (
dhpa_ferc714
.groupby(["report_year"]).demand_mwh.sum()
.reset_index()
)
annual_demand_mapped = (
dhpa_ferc714[dhpa_ferc714.eia_code.isin(hifld_pa_gdf.eia_code)]
.groupby(["report_year"]).demand_mwh.sum()
.reset_index()
.merge(annual_demand_ferc714, on="report_year"... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Historical Planning Area GeometriesCompile a GeoDataFrame that relates balancing authorities, their constituent utilities, and the collections of counties which are served by those utilities, across all the years for which we have EIA 861 data (2010-2018) | ba_util_county_gdf = georef_bas(ba_eia861, st_eia861, sales_eia861, census_gdf)
ba_util_county_gdf.info()
for year in (2010, 2014, 2018):
map_ba(ba_util_county_gdf.balancing_authority_id_eia.unique(), year, ba_util_county_gdf, save=True) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Output Simplified Annual BA Geometries* This takes half an hour so it's commented out.* Resulting shapefile is ~250MB compressed. Seems too big.* Need to figure out how to add explicity projection.* Need to figure out how to make each year's BA geometries its own layer. | #%%time
#ba_fips_simplified = (
# ba_util_county_gdf
# .assign(report_year=lambda x: x.report_date.dt.year)
# .drop([
# "report_date",
# "state",
# "state_id_fips",
# "county",
# "county_name_census",
# "utility_id_eia",
# "utility_name_eia"
# ], axis="column... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Compare HIFLD and EIA BA maps for 2018 | for ba_code in hifld_pa_gdf.ABBRV.unique():
if ba_code in ba_util_county_gdf.balancing_authority_code_eia.unique():
compare_hifld_eia_ba(ba_code, hifld_pa_gdf, ba_util_county_gdf) | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Time Evolution of BA GeometriesFor each BA we now have a collection of annual geometries. How have they changed over time? | for ba_code in ba_util_county_gdf.balancing_authority_code_eia.unique():
fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(20,20), sharex=True, sharey=True, facecolor="white")
for year, ax in zip(range(2010, 2019), axes.flat):
ax.set_title(f"{ba_code} ({year})")
ax.set_xticks([])
ax.se... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Merge Geometries with FERC 714Now that we have a draft of wht the BA and Utility level territories look like, we can merge those with the FERC 714 Respondent ID table, and see how many leftovers there are, and whether the BA and Utility geometires play well together.Before dissolving the boundaries between counties th... | utils_ferc714 = (
rids_ferc714.loc[
rids_ferc714.respondent_type == "utility",
["respondent_id_ferc714", "respondent_name_ferc714", "utility_id_eia", "respondent_type"]
]
)
bas_ferc714 = (
rids_ferc714.loc[
rids_ferc714.respondent_type == "balancing_authority",
["respondent_... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Check Geometries for Completeness* How many balancing authorities do we have geometries for?* How many utilities do we have geometries for?* Do those geometries cover all of the entities that report in FERC 714?* Do we have a geometry for every entity in every year in which it reports demand? Count BA & Util Geometri... | n_bas = len(rids_ferc714_gdf.balancing_authority_id_eia.unique())
logger.info(f"Found territories for {n_bas} unique Balancing Areas")
n_utils = len(rids_ferc714_gdf.loc[
(rids_ferc714_gdf.balancing_authority_id_eia.isnull()) &
(~rids_ferc714_gdf.utility_id_eia.isnull())
].utility_id_eia.unique())
logger.info(f... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Identify Missing Geometries* Within each year of historical data from 2010-2018, are there any entities (either BA or Utility) which **do** have hourly demand reported in the FERC 714, for whivh we do not have a historical geometry?* How many of them are there?* Why are they missing?* Do we have the geometires in adja... | problem_ids = pd.DataFrame()
for year in range(2010, 2019):
this_year_gdf = (
rids_ferc714_gdf
.loc[(rids_ferc714_gdf.report_date.dt.year==year) & (~rids_ferc714_gdf.geometry.isnull())]
)
# All BA IDs which show up in FERC 714:
ba_ids_ferc714 = (
rids_ferc714
.loc[rids_fe... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Dissolve to BA or Util* At this point we still have geometires at the county level.* This is 150,000+ records.* Really we just want a single geometry per respondent per year.* Dissolve based on year and respondent_id_ferc714.* Merge the annual per-respondent geometry with the rids_ferc714 which has more information* N... | %%time
dissolved_rids_ferc714_gdf = (
rids_ferc714_gdf.drop_duplicates(subset=["report_date", "county_id_fips", "respondent_id_ferc714"])
.dissolve(by=["report_date", "respondent_id_ferc714"])
.reset_index()
.loc[:, ["report_date", "respondent_id_ferc714", "geometry"]]
.merge(rids_ferc714, on="respo... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Select based on respondent type | dissolved_utils = dissolved_rids_ferc714_gdf.query("respondent_type=='utility'")
dissolved_bas = dissolved_rids_ferc714_gdf.query("respondent_type=='balancing_authority'") | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Nationwide BA / Util Maps* Still want to add the US state boundaries / coastlines to this for context. | unwanted_ba_ids = (
112, # Alaska
133, # Alaska
178, # Hawaii
301, # PJM Dupe
302, # PJM Dupe
303, # PJM Dupe
304, # PJM Dupe
305, # PJM Dupe
306, # PJM Dupe
)
for report_date in pd.date_range(start="2010-01-01", end="2018-01-01", freq="AS"):
ba_ax = (
dissolved_bas
... | _____no_output_____ | MIT | notebooks/historical_planning_areas.ipynb | catalyst-cooperative/electricity-demand-mapping |
Python Crash CourseMaster in Data Science - Sapienza UniversityHomework 2: Python ChallengesA.A. 2017/18Tutor: Francesco Fabbri InstructionsSo guys, here we are! **Finally** you're facing your first **REAL** homework. Are you ready to fight?We're going to apply all the P... | def fatt(n):
if(n == 0):
return 1
else:
return n*fatt(n-1)
fatt(12) | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
2. More math...Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 0 and 1000 (both included). The numbers obtained should be printed in a comma-separated sequence on a single line. (range and CFS) | ex_2=[str(x) for x in range (1001) if x%7 ==0 and x%5 !=0]
','.join(ex_2) | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
2. Count capital lettersIn this exercises you're going to deal with YOUR DATA. Indeed, in the list below there are stored your Favorite Tv Series. But, as you can see, there is something weird. There are too much CaPITal LeTTErs. Your task is to count the capital letters in all the strings and then print the total num... | tv_series = ['Game of THRroneS',
'big bang tHeOrY',
'MR robot',
'WesTWorlD',
'fIRefLy',
"i haven't",
'HOW I MET your mothER',
'friENds',
'bRon broen',
'gossip girl',
'prISon break',
... | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
3. A remarkUsing the list above, create a dictionary where the keys are Unique IDs and values the TV Series.You have to do the exercise keeping in mind these 2 constraints: 1. The order of the IDs has to be **dependent on the alphabetical order of the titles**, i.e. 0: first_title_in_alphabetical_order and so on...2. ... | # write here your code
newlst = []
for x in tv_series:
x.title()
newlst.append(x.title())
newlst
a=range(12)
b=sorted(newlst)
dict1=dict(zip(a,b))
dict1 | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
4. Dictionary to its maximumInvert the keys with the values in the dictionary built before. | # write here your code
inv= {v: k for k, v in dict1.items()}
inv | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
Have you done in **one line of code**? If not, try now! | # write here your code
already done :D | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
4. Other boring mathLet's talk about our beloved exams. Starting from the exams and CFU below, are you able to compute the weighted mean of them?Let's do it and print the result.Description of the data:exams[1] = $(title_1, grade_1)$cfu[1] = $CFU_1$ | exams = [('BIOINFORMATICS', 29),
('DATA MANAGEMENT FOR DATA SCIENCE', 30),
('DIGITAL EPIDEMIOLOGY', 26),
('NETWORKING FOR BIG DATA AND LABORATORY',28),
('QUANTITATIVE MODELS FOR ECONOMIC ANALYSIS AND MANAGEMENT','30 e lode'),
('DATA MINING TECHNOLOGY FOR BUSINESS AND SOCIETY... | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
5. Palindromic numbersWrite a script which finds all the Palindromic numbers, in the range [0,**N**] (bounds included). The numbers obtained should be printed in a comma-separated sequence on a single line.What is **N**?Looking at the exercise before:**N** = (Total number of CFU) x (Sum of all the grades)(details: htt... | def pali(n):
return str(n) == str(n)[::-1]
a=list(filter(pali, range(0,15876)))
print(a)
?filter | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
6. StackOverflow Let's start using your new best friend. Now I'm going to give other task, slightly more difficult BUT this time, just googling, you will find easily the answer on the www.stackoverflow.com. You can use the code there for solving the exercise BUT you have to understand the solution there **COMMENTING**... | # write here your code | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
6. BGiving this list of words below, after copying in a variable, explain and provide me a code for obtaining a **Bag of Words** from them.(Hint: use dictionaries and loops) ['theory', 'of', 'bron', 'firefly', 'thrones', 'break', 'bad', 'mother', 'firefly', "haven't", 'prison', 'big', 'friends', 'girl', 'westworld', '... | # write here your code | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
6. CAnd now, write down a code which computes the first 10 Fibonacci numbers(details: https://en.wikipedia.org/wiki/Fibonacci_number) | # write here your code | _____no_output_____ | MIT | 02/homework_day2.ipynb | Py101/py101-assignments-moka1992 |
Lineplot | # 200 values from the interval <0,100>, equidistantly divided
x = np.linspace(0,100,200)
y = np.sin(x)
# a line plot
plt.plot(x,y,'red')
plt.show() | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
scatterplot | # 200 random values from the interval <0,10>
x = 10*np.random.rand(200,1)
# 200 random values from the interval <0,15>
y = 15*np.random.rand(200,1)
# a scatter plot
plt.scatter(x,y)
plt.show() | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
histogram | # 200 random values from the interval <0,15>
y = 15*np.random.rand(200,1)
# a histogram with 20 bins
plt.hist(y,bins=20)
plt.show() | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
Graphs on common axes | # 200 values from the interval <0,100>, equidistantly divided
x = np.linspace(0,100,200)
# sin(x) values
y1 = np.sin(x)
# sin(x)*cos(x) values
y2 =(np.sin(x))*(np.cos(x))
# a line plot of sin(x), red line
plt.plot(x,y1,'red')
# a line plot of sin(x)*cos(x), blue line
plt.plot(x,y2,'blue')
plt.show() | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
Subplots | # the first figure
plt.subplot(2,1,1)
plt.plot(x,y1,'red')
plt.title('sin(x)')
# the second figure
plt.subplot(2,1,2)
plt.plot(x,y2,'blue')
plt.title('sin(x)*(cos(x))')
# automatically adjust the subplot parameters to give a specified padding
plt.tight_layout()
plt.show() | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
Legends | # import pandas
import pandas as pd
# import sklearn datasets
from sklearn import datasets
# load iris dataset
iris = datasets.load_iris()
# create dataframe
iris_df = pd.DataFrame(iris.data, columns=iris.feature_names)
# create target
iris_df['target'] = iris.target
# map the target values to the target names
iris... | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
Annotations | # the same code as before
plt.scatter(setosa['sepal length (cm)'],setosa['sepal width (cm)'],
marker ='o', color = 'red', label = 'setosa')
plt.scatter(versicolor['sepal length (cm)'],versicolor['sepal width (cm)'],
marker ='o', color = 'green', label = 'versicolor')
plt.scatter(virginica['sep... | _____no_output_____ | MIT | w3/w3-day_1/.ipynb_checkpoints/Matplotlib_tutorial-checkpoint.ipynb | bmskarate/lighthouseMain |
Part 0: Mining the webPerhaps the richest source of openly available data today is [the Web](http://www.computerhistory.org/revolution/networking/19/314)! In this lab, you'll explore some of the basic programming tools you need to scrape web data.> **Note.** The Vocareum platform runs in a cloud-based environment that... | import requests
response = requests.get('https://www.gatech.edu/')
webpage = response.text # or response.content for raw bytes
print(webpage[0:250]) # Prints the first hundred characters only | <!DOCTYPE html>
<html lang="en" dir="ltr"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/terms/"
xmlns:foaf="http://xmlns.com/foaf/0.1/"
xmlns:og="http://ogp.me/ns#"
xmlns:rdfs="http://www.w3.org/2000
| MIT | EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 1: Representing, transforming and visualizing data/Topic 6 + Notebook 6 (OPTIONAL): Mining the web/part6.ipynb | helpthx/Path_through_Data_Science_2019 |
**Exercise 1.** Given the contents of the GT home page as above, write a function that returns a list of links (URLs) of the "top stories" on the page.For instance, on Friday, September 9, 2016, here was the front page:The top st... | import re # Maybe you want to use a regular expression?
def get_gt_top_stories(webpage_text):
"""Given the HTML text for the GT front page, returns a list
of the URLs of the top stories or an empty list if none are
found.
"""
pattern = '''<a class="slide-link" href="(?P<url>[^"]+)"'''
return re... | Links to GT's top stories: ['https://www.news.gatech.edu/features/age-empowerment-meet-casey-aultman', 'https://news.gatech.edu/features/first-tech-governors-inauguration-mccamish', 'http://www.news.gatech.edu/features/you-should-come-georgia-tech']
| MIT | EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 1: Representing, transforming and visualizing data/Topic 6 + Notebook 6 (OPTIONAL): Mining the web/part6.ipynb | helpthx/Path_through_Data_Science_2019 |
A more complex exampleGo to [Yelp!](http://www.yelp.com) and look up `ramen` in `Atlanta, GA`. Take note of the URL: This URL encodes what is known as an _HTTP "get"_ method (or request). It basically means a URL with two parts: a _command_ followed by one or ... | url_command = 'https://yelp.com/search'
url_args = {'find_desc': "ramen",
'find_loc': "atlanta, ga"}
response = requests.get (url_command, params=url_args, timeout=60)
print ("==> Downloading from: '%s'" % response.url) # confirm URL
print ("\n==> Excerpt from this URL:\n\n%s\n" % response.text[0:100]) | ==> Downloading from: 'https://www.yelp.com/search?find_desc=ramen&find_loc=atlanta%2C+ga'
==> Excerpt from this URL:
<!DOCTYPE HTML>
<!--[if lt IE 7 ]> <html xmlns:fb="http://www.facebook.com/2008/fbml" class="ie6 ie
| MIT | EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 1: Representing, transforming and visualizing data/Topic 6 + Notebook 6 (OPTIONAL): Mining the web/part6.ipynb | helpthx/Path_through_Data_Science_2019 |
**Exercise 2.** Given a search topic, location, and a rank $k$, return the name of the $k$-th item of a Yelp! search. If there is no $k$-th item, return `None`.> The demo query above only gives you a website with the top 10 items, meaning you could only use it for $k \leq 10$. Figure out how to modify it to solve the p... | def find_yelp_item (topic, location, k):
"""Returns the k-th suggested item from Yelp! in Atlanta for the given topic."""
import re
if k < 1: return None
# Download page
url_command = 'http://yelp.com/search'
url_args = {'find_desc': topic,
'find_loc': location,
... | _____no_output_____ | MIT | EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 1: Representing, transforming and visualizing data/Topic 6 + Notebook 6 (OPTIONAL): Mining the web/part6.ipynb | helpthx/Path_through_Data_Science_2019 |
> Search queries on Yelp! don't always return the same answers, since the site is always changing! Also, your results might not match a query you do via your web browser (_why not?_). As such, you should manually check your answers. | item = find_yelp_item ('fried chicken', 'Atlanta, GA', 1)
print (item)
item = find_yelp_item ('fried chicken', 'Atlanta, GA', 5)
print (item)
# The most likely answer on September 11, 2018:
#assert item == 'Buttermilk Kitchen'
item = find_yelp_item('fried chicken', 'Atlanta, GA', 10)
print(item)
# Most lik... | None
| MIT | EdX/GTx: CSE6040x: FA18 - Computing for Data Analysis/Module 1: Representing, transforming and visualizing data/Topic 6 + Notebook 6 (OPTIONAL): Mining the web/part6.ipynb | helpthx/Path_through_Data_Science_2019 |
Main notebook for battery state estimation | import numpy as np
import pandas as pd
import scipy.io
import math
import os
import ntpath
import sys
import logging
import time
import sys
from importlib import reload
import plotly.graph_objects as go
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from keras.models import ... | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Config logging | reload(logging)
logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.DEBUG, datefmt='%Y/%m/%d %H:%M:%S') | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Load Data | train_names = [
'n10degC/601_Mixed1',
'n10degC/601_Mixed2',
'n10degC/604_Mixed3',
'n10degC/602_Mixed4',
'n10degC/602_Mixed5',
'n10degC/604_Mixed6',
'n10degC/604_Mixed7',
'n10degC/604_Mixed8',
'n20degC/610_Mixed1',
'n20degC/610_Mixed2',
'n20degC/611_Mixed3',
'n20degC/... | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Model training | EXPERIMENT = "lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test"
experiment_name = time.strftime("%Y-%m-%d-%H-%M-%S") + '_' + EXPERIMENT
print(experiment_name)
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
# Model definition
opt = tf.keras.optimizers.Adam(lr=0.00001)
model = Sequential()
model.add(LSTM... | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Testing | results = model.evaluate(test_x, test_y)
print(results) | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Data Visualization | # fig = go.Figure()
# fig.add_trace(go.Scatter(y=history.history['loss'],
# mode='lines', name='train'))
# fig.add_trace(go.Scatter(y=history.history['val_loss'],
# mode='lines', name='validation'))
# fig.update_layout(title='Loss trend',
# xaxis_title='epoch',
... | _____no_output_____ | Apache-2.0 | battery-state-estimation/experiments/lg/lstm_soc_percentage_lg_negative_temp_500_steps_drive_cycle_test.ipynb | KeiLongW/battery-state-estimation |
Regression Analysis: Seasonal Effects with Sklearn Linear RegressionIn this notebook, you will build a SKLearn linear regression model to predict Yen futures ("settle") returns with *lagged* Yen futures returns. | # Futures contract on the Yen-dollar exchange rate:
# This is the continuous chain of the futures contracts that are 1 month to expiration
yen_futures = pd.read_csv(
Path("yen.csv"), index_col="Date", infer_datetime_format=True, parse_dates=True
)
yen_futures.head()
# Trim the dataset to begin on January 1st, 1990
... | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Data Preparation Returns | # Create a series using "Settle" price percentage returns, drop any nan"s, and check the results:
# (Make sure to multiply the pct_change() results by 100)
# In this case, you may have to replace inf, -inf values with np.nan"s
yen_futures['Return'] = (yen_futures[["Settle"]].pct_change() * 100)
returns = yen_futures.re... | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Lagged Returns | # Create a lagged return using the shift function
yen_futures['Lagged_Return'] = yen_futures['Return'].shift()
yen_futures = yen_futures.dropna()
yen_futures.tail() | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Train Test Split | # Create a train/test split for the data using 2018-2019 for testing and the rest for training
train = yen_futures[:'2017']
test = yen_futures['2018':]
# Create four dataframes:
# X_train (training set using just the independent variables), X_test (test set of of just the independent variables)
# Y_train (training set ... | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Linear Regression Model | # Create a Linear Regression model and fit it to the training data
from sklearn.linear_model import LinearRegression
# Fit a SKLearn linear regression using just the training set (X_train, Y_train):
model = LinearRegression()
model.fit(X_train, y_train) | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Make predictions using the Testing DataNote: We want to evaluate the model using data that it has never seen before, in this case: X_test. | # Make a prediction of "y" values using just the test dataset
predictions = model.predict(X_test)
# Assemble actual y data (Y_test) with predicted y data (from just above) into two columns in a dataframe:
Results = y_test.to_frame()
Results["Predicted Return"] = predictions
# Plot the first 20 predictions vs the true v... | _____no_output_____ | ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
Out-of-Sample PerformanceEvaluate the model using "out-of-sample" data (X_test and y_test) | from sklearn.metrics import mean_squared_error
# Calculate the mean_squared_error (MSE) on actual versus predicted test "y"
mse = mean_squared_error(Results["Return"],Results["Predicted Return"])
# Using that mean-squared-error, calculate the root-mean-squared error (RMSE):
rmse = np.sqrt(mse)
print(f"Out-of-Sample Ro... | Out-of-Sample Root Mean Squared Error (RMSE): 0.41545437184712763
| ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
In-Sample PerformanceEvaluate the model using in-sample data (X_train and y_train) | # Construct a dataframe using just the "y" training data:
in_sample_results = y_train.to_frame()
# Add a column of "in-sample" predictions to that dataframe:
in_sample_results["In-sample Predictions"] = model.predict(X_train)
# Calculate in-sample mean_squared_error (for comparison to out-of-sample)
in_sample_mse =... | In-sample Root Mean Squared Error (RMSE): 0.5962037920929946
| ADSL | Starter_Code/regression_analysis.ipynb | focraniv/A-Yen-for-the-Future |
酷我音樂- 下載酷我音樂平台上電台的「專輯」音檔 載入套件 | import re
import os
import time
import requests
from bs4 import BeautifulSoup | _____no_output_____ | MIT | KUWO_ALBUM.ipynb | TLYu0419/KUWO |
設定爬蟲參數 | headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.63',
'Cookie': '_ga=GA1.2.841063431.1603504850; Hm_lvt_cdb524f42f0ce19b169a8071123a4797=1611556993; _gid=GA1.2.997533225.1613194048; Hm_lpvt_cdb524f42f0ce... | _____no_output_____ | MIT | KUWO_ALBUM.ipynb | TLYu0419/KUWO |
爬取資料 蒐集連結清單 | page = 1
links = []
while True:
# 生成網址
url = 'http://www.kuwo.cn/api/www/album/albumInfo?albumId=547562&pn={}&rn=30'.format(page)
# 請求資料
resp = requests.get(url, headers=headers)
time.sleep(0.5)
try:
musicList = [i['rid'] for i in resp.json()['data']['musicList']]
# 保存資訊
... | 1 : 30
2 : 60
status_code: 504 , Retry
status_code: 504 , Retry
status_code: 504 , Retry
3 : 90
4 : 120
status_code: 504 , Retry
5 : 150
6 : 180
7 : 210
8 : 240
9 : 270
10 : 300
11 : 330
12 : 360
13 : 390
14 : 420
status_code: 504 , Retry
15 : 450
16 : 480
17 : 510
18 : 540
19 : 570
status_code:... | MIT | KUWO_ALBUM.ipynb | TLYu0419/KUWO |
下載連結音檔 | # os.mkdir('./musics')
# 已下載的音樂清單
download_list = [int(i.split('_',-1)[0]) for i in os.listdir('./musics')]
len(download_list)
# 排除已下載的音樂
links = [link for link in links if link not in download_list]
len(links)
for link in links:
# 取音檔摘要
url = 'http://www.kuwo.cn/play_detail/{}'.format(link)
resp = request... | Succed: 7090145 请你不要告诉我,你最爱的人不是我(一个人听)_蕊希Erin_单曲在线试听_酷我音乐
Succed: 7090146 为什么,你就不喜欢我了(一个人听)_蕊希Erin_单曲在线试听_酷我音乐
Succed: 76240867 ”我不是傻,只是懒得计较”_蕊希Erin_单曲在线试听_酷我音乐
Succed: 83795941 你有多久没对另一半说我爱你了?_蕊希Erin_单曲在线试听_酷我音乐
Succed: 57690089 会有人拿着戒指对你笑,说余生请多指教。 (节目)_蕊希Erin_单曲在线试听_酷我音乐
Succed: 57151470 ” 我月薪三万,拒绝给女友买两万的包。 ”_蕊... | MIT | KUWO_ALBUM.ipynb | TLYu0419/KUWO |
異常狀況排除- 通常是檔案名稱有非法字元,或者request的速度過快被擋~ | soup.find('title').text
requests.get(music_link).json()['url']
music_name = '66823804_蕊希专访 陈乔恩:爱自己,是终身浪漫的开始_蕊希Erin_单曲在线试听_酷我音乐.mp3'
with open('./musics/{}.mp3'.format(str(link) + '_' + music_name), 'wb') as f:
f.write(music_content) | _____no_output_____ | MIT | KUWO_ALBUM.ipynb | TLYu0419/KUWO |
Make cluster plot | _ = pylab.hist(data['nunique'][data['nunique']!= 0], 50)
def setup_clusters(width=1500, xoffset=0, yoffset=0, **params):
kwargs = dict(xticks=False, yticks=False, grid=False, tickmarks=False)
kwargs.update(params)
ax = setup(xr=[-width+xoffset,width+xoffset], yr=[-width+yoffset,width+yoffset], **kwargs)
... | _____no_output_____ | MIT | reddit/visualize.ipynb | ajmendez/explore |
Build data.json | vizit = json.load(open('/Users/ajmendez/data/reddit/vizit_data.json', 'r'))
ii = np.where(data['age'] > 0)
ageit = dict(nodes=[], edges=[])
node_ids = []
for node in vizit['nodes']:
subreddit = node['label']
i = np.where( (data['subreddit'] == subreddit) & (data['age'] > 0) )[0]
if len(i) != 0:
... | _____no_output_____ | MIT | reddit/visualize.ipynb | ajmendez/explore |
Class AttributesIn practice a dog as a color, breed, age, and other attributes, and it can do things like eat, run, sleep, bark etc. | class Dog:
# Atributes
age = 0
name = 'noname'
breed = 'nobreed'
color = 'nocolor'
my_dog = Dog()
print('{} is a {}-year old {} {}.'.format(my_dog.name,my_dog.age,my_dog.color,my_dog.breed))
my_dog = Dog()
my_dog.age = 2
my_dog.name = 'Fido'
my_dog.color = 'brown'
my_dog.breed = 'Labradoodle'
p... | Fido is a 2-year old brown Labradoodle.
| MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Object Constructor | class Dog:
def __init__(self, age ,name ,breed ,color):
self.age = age
self.name = name
self.breed = breed
self.color = color
my_dog = Dog('4','Coco','Corgie','Brown')
print('{} is a {}-year old {} {}.'.format(my_dog.name,my_dog.age,my_dog.color,my_dog.breed))
class Dog:
def __in... | Ralph is a 7-year old gray Chihuahua.
mammal
| MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
A physics example | class Projectile():
gravityConstant = 9.81 # m/s^2
def __init__(self, initVelocity):
self.initVelocity = initVelocity
#self.time = time
def getHeight(self, time):
return self.initVelocity*time-.5*self.gravityConstant*time**2
ball = Projectile(initVelocity = 10)
height = ba... | _____no_output_____ | MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Inhertiance | class childName(parentName):
## list of all new, sub-class specific attributes and methods
# including the sub-class constructor
class Animal:
#Animal Constructor
def __init__(self,age = 0, weight = 0, animal_is_alive = True):
self.age = age
self.weigt = weight
self.an... | <bound method Dog.bark of <__main__.Dog object at 0x7f3e86e1ba30>> <bound method Dog.bark of <__main__.Dog object at 0x7f3e86e1ba30>> <bound method Dog.bark of <__main__.Dog object at 0x7f3e86e1ba30>> | MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Overloading and Multiple Inheritances | class MotherDog(Animal):
def __init__(self,age = 0,weight = 0,animal_is_alive = True, breed = 'nobreed', color = 'nocolor', name = 'noname',):
def bark(self, num_barks = 3):
for i in range(num_barks):
print('arf', end = ' ')
class FatherDog(Animal) | _____no_output_____ | MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Polymorphism | Tito = FatherDog(age=12,breed='Doberman',) | _____no_output_____ | MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Overloading Operations and Functions | class Vector:
def __init__(self,x_comp,y_comp):
self.x_comp = x_comp
self.y_comp = y_comp
def __abs__(self):
return (self.x_comp**2+self.y_comp**2)**(0.5)
x = Vector(1,2)
print(x)
class Vector:
def __init__(self,x_comp,y_comp):
self.x_comp = x_comp
self.y_comp ... | _____no_output_____ | MIT | Object Oriented Programming.ipynb | Ryan-Bui/DATA3401 |
Copyright 2020 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0
# 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 the License is d... | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
TensorFlow Addons Optimizers: ConditionalGradient View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook OverviewThis notebook will demonstrate how to use the Conditional Graident Optimizer from the Addons package. ConditionalGradient> Constraining the paramete... | import tensorflow as tf
import tensorflow_addons as tfa
from matplotlib import pyplot as plt
# Hyperparameters
batch_size=64
epochs=10 | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Build the Model | model_1 = tf.keras.Sequential([
tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'),
tf.keras.layers.Dense(64, activation='relu', name='dense_2'),
tf.keras.layers.Dense(10, activation='softmax', name='predictions'),
]) | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Prep the Data | # Load MNIST dataset as NumPy arrays
dataset = {}
num_validation = 10000
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# Preprocess the data
x_train = x_train.reshape(-1, 784).astype('float32') / 255
x_test = x_test.reshape(-1, 784).astype('float32') / 255 | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
| Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Define a Custom Callback Function | def frobenius_norm(m):
"""This function is to calculate the frobenius norm of the matrix of all
layer's weight.
Args:
m: is a list of weights param for each layers.
"""
total_reduce_sum = 0
for i in range(len(m)):
total_reduce_sum = total_reduce_sum + tf.math.reduce_sum(m[i]**... | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Train and Evaluate: Using CG as OptimizerSimply replace typical keras optimizers with the new tfa optimizer | # Compile the model
model_1.compile(
optimizer=tfa.optimizers.ConditionalGradient(
learning_rate=0.99949, lambda_=203), # Utilize TFA optimizer
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
history_cg = model_1.fit(
x_train,
y_train,
batch_size=batch_size,... | Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 5s 85us/sample - loss: 0.3745 - accuracy: 0.8894 - val_loss: 0.2323 - val_accuracy: 0.9275
Epoch 2/10
60000/60000 [==============================] - 3s 50us/sample - loss: 0.1908 - accuracy: 0.9430 - val_loss: 0.... | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Train and Evaluate: Using SGD as Optimizer | model_2 = tf.keras.Sequential([
tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'),
tf.keras.layers.Dense(64, activation='relu', name='dense_2'),
tf.keras.layers.Dense(10, activation='softmax', name='predictions'),
])
SGD_frobenius_norm_of_weight = []
SGD_get_weight_norm = tf.k... | Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 3s 46us/sample - loss: 0.9498 - accuracy: 0.7523 - val_loss: 0.4306 - val_accuracy: 0.8844
Epoch 2/10
60000/60000 [==============================] - 2s 41us/sample - loss: 0.3851 - accuracy: 0.8916 - val_loss: 0.... | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Frobenius Norm of Weights: CG vs SGD The current implementation of CG optimizer is based on Frobenius Norm, with considering Frobenius Norm as regularizer in the target function. Therefore, we compare CG’s regularized effect with SGD optimizer, which has not imposed Frobenius Norm regularizer. | plt.plot(
CG_frobenius_norm_of_weight,
color='r',
label='CG_frobenius_norm_of_weights')
plt.plot(
SGD_frobenius_norm_of_weight,
color='b',
label='SGD_frobenius_norm_of_weights')
plt.xlabel('Epoch')
plt.ylabel('Frobenius norm of weights')
plt.legend(loc=1) | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
Train and Validation Accuracy: CG vs SGD | plt.plot(history_cg.history['accuracy'], color='r', label='CG_train')
plt.plot(history_cg.history['val_accuracy'], color='g', label='CG_test')
plt.plot(history_sgd.history['accuracy'], color='pink', label='SGD_train')
plt.plot(history_sgd.history['val_accuracy'], color='b', label='SGD_test')
plt.xlabel('Epoch')
plt.yla... | _____no_output_____ | Apache-2.0 | site/en-snapshot/addons/tutorials/optimizers_conditionalgradient.ipynb | ilyaspiridonov/docs-l10n |
**Amazon Lookout for Equipment** - 익명화한 익스펜더 데이터셋에 대한 데모*파트 5: 정기적인 추론 호출 스케줄링* | BUCKET = '<YOUR_BUCKET_NAME_HERE>'
PREFIX = 'data/scheduled_inference' | _____no_output_____ | MIT-0 | notebooks/5_inference_scheduling.ipynb | youngmki/lookout-for-equipment-demo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.