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 |
|---|---|---|---|---|---|
No Water | no_water_loops = collections.defaultdict(list)
no_water_path = Path('no_water')
for f in no_water_path.iterdir():
if 'loops_hist' in f.name:
k = float(f.name.split('_')[3])
with f.open('rb') as iv:
d = pickle.load(iv)
no_water_loops[k].extend(d[-1]) | _____no_output_____ | Unlicense | paper/analysis/Loops.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
With water | water_loops = collections.defaultdict(list)
water_path = Path('with_water')
for f in water_path.iterdir():
if 'loops_hist' in f.name:
k = float(f.name.split('_')[3])
with f.open('rb') as iv:
d = pickle.load(iv)
water_loops[k].extend(d[-1]) | _____no_output_____ | Unlicense | paper/analysis/Loops.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
Water rev | water_rev_loops = collections.defaultdict(list)
water_rev_path = Path('with_water_rev')
for f in water_rev_path.iterdir():
if 'loops_hist' in f.name and 'rt1' in f.name:
k = float(f.name.split('_')[3])
kr = float(f.name.split('_')[4])
if kr != 0.001:
continue
print(k,kr)
... | _____no_output_____ | Unlicense | paper/analysis/Loops.ipynb | jkrajniak/paper-cg-md-simulations-of-polymerization-with-forward-and-backward-reactions |
Transformations & Transformation Tuning Parametersdefine the transformations we want to do, some transformations will have parameters (e.g. base of log tranform (or no transform), type of scaling, whether or not to add column combinations (e.g. age * hours-per-week) Below is the pipeline for captail-gain/lost. We want... | cap_gain_loss_pipeline = Pipeline([
('selector', DataFrameSelector(attribute_names=['capital-gain', 'capital-loss'])),
('imputer', Imputer()),
# tune Log trasformation base (or no transformation); update: tuned - chose base e
('custom_transform', CustomLogTransform(base=math.e)),
... | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Below is the pipeline for the rest of numeric features: | num_pipeline = Pipeline([
('selector', DataFrameSelector(attribute_names=['age', 'education-num', 'hours-per-week'])),
('imputer', Imputer()),
# tune age * hours-per-week; update: tuned -chose not to include
#('combine_agehours', CombineAgeHoursTransform()),
# tune MinMax vs Stan... | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Pipeline that simply gets the categorical/encoded columns from the previous transformation (which used `oo-learning`) | append_categoricals = Pipeline([
('append_cats', DataFrameSelector(attribute_names=one_hot_transformer.encoded_columns)) # already encoded
]) | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Below is the pipeline for combining all of the other pipelines | # combine pipelines
transformations_pipeline = FeatureUnion(transformer_list=[
("cap_gain_loss_pipeline", cap_gain_loss_pipeline),
("num_pipeline", num_pipeline),
("cat_pipeline", append_categoricals),
]) | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Choose the transformations to tune, below: Below calculates the a standard value for `scale_pos_weight` based on the recommendation from http://xgboost.readthedocs.io/en/latest/parameter.html> Control the balance of positive and negative weights, useful for unbalanced classes. A typical value to consider: sum(negative ... | model = LogisticRegression(random_state=42,
#penalty='l2',
C=1.0,
)
full_pipeline = Pipeline([
('preparation', transformations_pipeline),
#('pca_chooser', ChooserTransform()), # PCA option lost; didn't include
#('feature_selection',... | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Tuning strategy according to https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/ | from scipy.stats import randint, uniform, expon
model_param_dict = {
# 1st
'model__penalty': ['l1', 'l2'],
'model__C': uniform(0.001, 100),
}
# actual hyper-parameters/options to tune for transformations.
transformation_parameters = {
#'preparation__num_pipeline__imputer__strategy': ['m... | _____no_output_____ | MIT | data_scientist_nanodegree/projects/p1_charityml/custom/Logistic_RandomizedSearch_sklearn.ipynb | shane-kercheval/udacity |
Descarga de excels | from datetime import datetime,timedelta
Inicio_programa=datetime.now() | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Importo los paquetes | import os
import tabula
import re
from openpyxl import Workbook,load_workbook
import pandas as pd
import shutil
from natsort import natsorted
path_local="/home/rodrigo/Scrapper_Sueldos_Municipales" | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Verificación de carpetas | path_folder_pdf=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/pdf"
lista_folder_pdf=natsorted(os.listdir(path_folder_pdf))
for i in lista_folder_pdf:
if re.search("Sueldos",i) is None:
lista_folder_pdf.remove(i)
lista_folder_pdf
index_carpeta_a_modificar=-1
folder_pdf_a_convertir=lista_folder_... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Crea la carpeta donde se van a guardar los excel en crudo | path_folder_pdf_a_convertir=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/pdf/"+folder_pdf_a_convertir
Lista_pdf_nuevos=natsorted(os.listdir(path_folder_pdf_a_convertir))
Lista_nombres_secretarias=[re.sub("\.pdf","",i) for i in Lista_pdf_nuevos]
try :
os.mkdir(path_local+"/Gasto_Publico_Argentino_f... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Acomodo de excel sucios | # Estos 2 nombres no me gustan
path_carpetas_excels_sucios=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza"
carpetas_excels_sucios=natsorted(os.listdir(path_carpetas_excels_sucios))
for carpeta_secretaria in carpetas_excels_sucios:
path_excels_sin_modificar= path_carpetas_e... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Crea la carpeta donde se almacenan los excel | path_carpeta_sueldos_nuevos=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"
try:
os.mkdir(path_carpeta_sueldos_nuevos)
except:
pass
nombres_secciones_secretarias=natsorted(os.listdir(path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/secciones"))
#print... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Re-acomodo los excel en cada subcarpeta | lista_secretarias_sin_excepciones=["salario_ambiente",
"salario_control",
"salario_deporte_turismo",
"salario_hacienda",
"salario_ilar",
"salario_modernizacion",
"salario_movilidad",
"salario_obras",
"salario_salud",
"sal... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Manejo de excepciones Salario Cultura | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_cultura"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_cultura"
lista_secretaria=natsorted(os.listdir(path_secretaria))
s... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario Desarrollo Economico | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_desarrollo_economico"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_desarrollo_economico"
lista_secretaria=natsorted(os.li... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario desarrollo humano | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_desarrollo_humano"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_desarrollo_humano"
lista_secretaria=natsorted(os.listdir(... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario Genero | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_genero_ddhh"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_genero_ddhh"
lista_secretaria=natsorted(os.listdir(path_secreta... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario Gobierno | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_gobierno"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_gobierno"
lista_secretaria=natsorted(os.listdir(path_secretaria))
... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario intendencia | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_intendencia"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_intendencia"
lista_secretaria=natsorted(os.listdir(path_secreta... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Salario Planeamiento | path_limpieza_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza/salario_planeamiento"
path_secretaria=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos/salario_planeamiento"
lista_secretaria=natsorted(os.listdir(path_secre... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Elimina la carpeta "Excels_proceso_limpieza" | shutil.rmtree(path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/Excels_proceso_limpieza") | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Creo los archivos finales | path_folder_carpeta=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"
lista_secretarias=natsorted(os.listdir(path_folder_carpeta))
path_carpeta_prueba=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/carpeta_prueba"
for secretaria in lista_secretarias:
path_... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Elimina las carpetas | for secretarias in os.listdir(path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"):
for archivos_secretaria in os.listdir(os.path.join(path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos",secretarias)):
try:
... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Reviso la columna 1 de todos los excel y muevo los numeros a la segunda columna | path=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"
lista_secretarias=natsorted(os.listdir(path))
for secretaria in lista_secretarias:
path_secretaria=os.path.join(path,secretaria)
lista_archivos=natsorted(os.listdir(path_secretaria))
for archivo in lista_ar... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Reemplazo las comas por puntos | path=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"
for secretaria in natsorted(os.listdir(path)):
lista_secretaria=natsorted(os.listdir(os.path.join(path,secretaria)))
for archivo in lista_secretaria:
path_archivo=os.path.join(os.path.join(path,secretar... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Esto revisa unos numeros extras que salen random luego de los 2 decimales | path=path_local+"/Gasto_Publico_Argentino_files/Salarios_Rosario/XLSX/"+carpeta_especifica+"_Sueldos"
lista_secretarias=natsorted(os.listdir(path))
for columna in [2,3,4]:
for secretaria in lista_secretarias:
lista_archivos=natsorted(os.listdir(os.path.join(path,secretaria)))
for archivo in lista_ar... | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Mido cuanto tardo el programa (aproximadamente) | Finalizacion_programa=datetime.now()
tiempo=Finalizacion_programa-Inicio_programa
tiempo_medido=str(timedelta(seconds=tiempo.seconds))[2:]
tiempo_medido | _____no_output_____ | MIT | Fase_2.ipynb | rodrigotesone1997/Limpieza_Datos_Municipales |
Lasso and Elastic Net for Sparse SignalsEstimates Lasso and Elastic-Net regression models on a manually generatedsparse signal corrupted with an additive noise. Estimated coefficients arecompared with the ground-truth. | print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
# #############################################################################
# Generate some sparse data to play with
np.random.seed(42)
n_samples, n_features = 50, 100
X = np.random.randn(n_samples, n_features... | _____no_output_____ | MIT | sklearn/sklearn learning/demonstration/auto_examples_jupyter/linear_model/plot_lasso_and_elasticnet.ipynb | wangyendt/deeplearning_models |
Campus RecruitmentIn this notebook we will try to answer these questions.* Which factor influenced a candidate in getting placed?* Does percentage matters for one to get placed?* Which degree specialization is much demanded by corporate?* Play with the data conducting all statistical tests.At the end we'll use Decisi... | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.read_csv("../input/factors-affecting-campus-placement/Placement_Data_Full_Class.csv")
df.head()
df.describe()
df.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 215 entries, 0 to 214
Data columns (total 15 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 sl_no 215 non-null int64
1 gender 215 non-null object
2 ssc_p 215 non-null ... | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
We can observe some Null rows for the columns salary | df.isna().any()
df['salary'].mean()
df.groupby('degree_t')['salary'].mean() | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Student in Science and Tech get more money than others | df.groupby('gender')['salary'].mean() | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Male earn more money than female Plot data | sns.barplot(x='gender',y='salary',data=df,palette="Blues_d")
sns.barplot(x='degree_t',y='salary',data=df,palette="Blues_d")
sns.countplot(x='gender',data=df,palette="Blues_d")
sns.barplot(x="workex",y="salary",data=df,palette="Blues_d")
sns.barplot(x="status",y="degree_p",data=df,palette="Blues_d") | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
placed person arehigher degree than not_placed | sns.barplot(x="workex",y="degree_p",data=df,palette="Blues_d")
sns.barplot(x="gender",y="degree_p",data=df,palette="Blues_d") | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Female have better degree than male | sns.barplot(x="ssc_b",y="salary",data=df,palette="Blues_d")
sns.barplot(x="specialisation",y="salary",data=df,palette="Blues_d") | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Global plot | sns.pairplot(data=df,palette="Blues_d") | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
We Can see the correlation (linearity) between different columns | df.groupby('gender')['status'].value_counts() | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Male are more recruited than female however we saw above that female got better mark than male | # Check the correlation
sns.heatmap(df.corr(),cmap="Blues") | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
if we look at the salary we can say that the degree nor the gender of anything have a real impact to the salary of the student | sns.kdeplot(df['salary'])
# we get only categorical data
cols = df.columns
num_cols = df._get_numeric_data().columns
num_cols
categorical_col = list(set(cols) - set(num_cols))
for i in categorical_col:
plt.figure()
sns.stripplot(x=i, y="salary",hue='gender',data=df, palette="Set1", dodge=True)
df.groupby('deg... | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Student in Commerce are more placed than Prediction a DecisionTreeClassifier | from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import confusion_matrix
df.columns
labelEncode = LabelEncoder()
for i in categorical_col:
df[i] = labelEncode.fit_transform(df[i])
df
# ... | _____no_output_____ | Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Build DecisionTreeClassifier | decisionTree = DecisionTreeClassifier()
decisionTree.fit(x_train,y_train)
decisionTree.score(x_test,y_test)
y_pred = decisionTree.predict(x_test)
y_pred
len(y_test)
y_test.head()
y_test = y_test.tolist()
number_error = 0
for i in range(len(y_test)):
if y_test[i] != y_pred[i]:
number_error += 1
num... | confusion matrix:
[[12 1]
[ 0 30]]
| Apache-2.0 | campus-recruitment-97-score.ipynb | theyazilimci/KaggleProject |
Distributions | from empiricaldist import Pmf | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
Probability Mass Functions PMF- for dicrete outcomes (ex: head or tails)- maps each possible outcome to it's probability | # Representing the outcome of a coin toss
coin = Pmf()
coin['heads'] = 1/2
coin['tails'] = 1/2
coin
# Create a probability mass function for a series of die outcomes
die = Pmf.from_seq([1, 2, 3, 4, 5, 6])
die | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
All outcomes in the sequence appear once, so they all have the same probability, 1/6 | letters = Pmf.from_seq(list('Mississippi'))
letters | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
'M' appears once, so probability = 1/11 = 0.0909'i' appears 4 times, so probability = 4/11 = 0.3636and so on... | letters['s']
# Avoid KeyError
try:
letters['t']
except KeyError as e:
print("Please choose a letter contained in the Pmf") | Please choose a letter contained in the Pmf
| MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
You can also call a Pmf as if it were a function | letters('s') | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
Calling a quantity that does not exists in the distribution will yield a 0, not an error | letters('t') | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
Can also call some of the elements in the distribution | die([1,4,6]) | _____no_output_____ | MIT | notebooks/chap03me.ipynb | mdominguez2010/ThinkBayes2 |
Step 0: This analysis research question will require several different datasets: 1. The `RAW_us_confirmed_cases.csv` file from the [Kaggle repository](https://www.kaggle.com/antgoldbloom/covid19-data-from-john-hopkins-university?select=RAW_us_confirmed_cases.csv) of John Hopkins University COVID-19 data.2. The [CDC d... | # setup- county of interest
# Montgomery, MD
state = 'Maryland'
st = 'MD'
county = 'Montgomery' | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Get Cases data | # Unzip cases file
os.chdir('data_raw')
with ZipFile('RAW_us_confirmed_cases.csv.zip') as zipfiles:
zipfiles.extractall()
os.chdir('..')
os.getcwd()
# load cases data
raw = pd.read_csv('data_raw/RAW_us_confirmed_cases.csv')
raw.columns | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Get Mask policy data | # get mask policy data
'https://data.cdc.gov/resource/62d6-pm5i.json?state_tribe_territory=TX&county'
base_url = 'https://data.cdc.gov/resource/62d6-pm5i.json?state_tribe_territory={st}&county_name={county}'
params = {
'st' : st,
'county' : county + ' County'
}
mask_url = base_url.format(**params)
masks_json... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Get mask compliance data | # get mask compliance data
compliance_url = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/mask-use/mask-use-by-county.csv'
compliance_df = pd.read_csv(compliance_url)
compliance_df.head() | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Filter based on given county | # filter
cases_filter = raw.loc[(raw.Province_State==state) & (raw.Admin2==county)].copy().reset_index(drop=True)
fips_county = int('10' + masks_df.fips_county[0])
compliance_filter = compliance_df.loc[compliance_df.COUNTYFP==fips_county].copy().reset_index(drop=True) | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Step 1: Analyze The common question that you are to answer is:- How did masking policies change the progression of confirmed COVID-19 cases from February 1, 2020 through October 15, 2021? Answering this question can be a little tricky - and it will be useful for you all (whole class) to discuss this on Slack. We will... | # additional data
pop = 1062061 # given
sq_mi = 491.25 # given
sq_km = 1272.34 # given | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Cases dataset | # cases have dates in columns- transpose to have each entry as rows
# also convert dates to datetime
cases = cases_filter[cases_filter.columns[11:]].T.reset_index().rename(columns={'index':'date', 0:'cases'})
cases.date = pd.to_datetime(cases.date)
#quick visualization
cases.plot(x='date', y='cases')
# cases per pop... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Masks dataset | # look at data types
for col in masks_df.columns:
print('Data type for column {} is {}'.format(col, type(masks_df[col][0])))
# convert data types
# dates to datetime
# order_code to int
masks_df.date = pd.to_datetime(masks_df.date)
masks_df.order_code = masks_df.order_code.astype(int)
# quick visualization
masks... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Mask compliance dataset | # also setup as columns --> transpose to show each entry as rows
# also show as magnitude
mask_comp = compliance_filter.drop(columns=['COUNTYFP']).T.reset_index().rename(columns={'index':'response',0:'pct_pop'})
mask_comp['pop'] = mask_comp.pct_pop * pop
mask_comp | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Merging datasets | # helper function
def case_per_pop(df, subset):
"""
Helper function to join mask compliance population % with cases dataset
df: pd.DataFrame
Cases dataframe
subset: str
String of mask compliance category
Returns: new pd.DataFrame with columns added for population given mask complian... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Getting daily cases | # get daily cases- daily difference between total cases
cases_merge['daily_cases'] = cases_merge.cases - cases_merge.cases.shift(1)
# quick visualization
cases_merge.plot(x='date', y='daily_cases') | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Get rolling average | # Helper function
def get_rolling_avg(df, days):
col_name = 'rolling_avg_' + str(days)
df[col_name] = df.daily_cases.rolling(days).mean()
return df
# get rolling average- 7 day
cases_merge = get_rolling_avg(cases_merge, 7)
# get rolling average- 14 day
cases_merge = get_rolling_avg(cases_merge... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Getting change in daily cases | # helper function
def get_pct_chg(df, days):
col_name = 'pct_chg_' + str(days) + 'D_avg'
pct_col = 'rolling_avg_' + str(days)
df[col_name] = df[pct_col].pct_change(1)
return df
# get pct change- 7 days RA
cases_merge = get_pct_chg(cases_merge, 7)
# get pct change- 14 days RA
cases_merge = ... | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Save to file | # save cleaned dataset to file
cases_merge.to_csv('data_clean/cases_clean.csv', index=False) | _____no_output_____ | MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Step 2: Visualize In this step we want you to create a graph that visualizes how the course of the disease was changed by masking policies. For your county, you should create a time series showing the changes in the derivative function of the rate of infection. Your graph should indicate days where masking policies we... | # read from file
cases = pd.read_csv('data_clean/cases_clean.csv')
cases.head()
# helper function- get masked array
def get_ma(var, order):
return np.ma.masked_where(cases.order_code==order, cases[var])
# get variables
x = pd.to_datetime(cases.date)
# get masked arrays (for different masking orders)
daily_mas... | C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\stride_tricks.py:256: UserWarning: Warning: converting a masked element to nan.
args = [np.array(_m, copy=False, subok=subok) for _m in args]
| MIT | A4-Common-Analysis.ipynb | emi90/data-512-a4 |
Gaussian bayes classifierIn this assignment we will use a Gaussian bayes classfier to classify our data points. Import packages | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
from sklearn.metrics import classification_report
from matplotlib import cm | _____no_output_____ | MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Load training dataOur data has 2D feature $x1, x2$. Data from the two classes is are in $\texttt{class1_train}$ and $\texttt{class2_train}$ respectively. Each file has two columns corresponding to the 2D feature. | class1_train = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L3/class1_train').to_numpy()
class2_train = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L... | _____no_output_____ | MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Visualize training dataGenerate 2D scatter plot of the training data. Plot the points from class 1 in red and the points from class 2 in blue. | import seaborn as sns
classes = ['class-1','class-2']
for i in range(class1_train.shape[0]):
plt.scatter(class1_train[i][0],class1_train[i][1] ,c="red",alpha=0.6, edgecolors='none')
# plt.legend(loc='best', fontsize=16)
plt.xlabel('Growth %')
plt.ylabel('Population')
for j in range(class2_train.... | /usr/local/lib/python3.6/dist-packages/statsmodels/tools/_testing.py:19: FutureWarning: pandas.util.testing is deprecated. Use the functions in the public API at pandas.testing instead.
import pandas.util.testing as tm
| MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Maximum likelihood estimate of parametersWe will model the likelihood, $P(\mathbf{x}|C_1)$ and $P(\mathbf{x}|C_2)$ as $\mathcal{N}(\mathbf{\mu_1},\Sigma_1)$ and $\mathcal{N}(\mathbf{\mu_2},\Sigma_2)$ respectively. The prior probability of the classes are called, $P(C_1)=\pi_1$ and $P(C_2)=\pi_2$.The maximum likelihood... | def calculate_pi_1():
num = class1_train.shape[0]
deno = class1_train.shape[0] + class2_train.shape[0]
return num/deno
def calculate_pi_2():
num = class2_train.shape[0]
deno = class1_train.shape[0] + class2_train.shape[0]
return num/deno
def calculate_mu_1():
return class1_train.mean(axis=0)
def calcul... | Pi-1 0.8040201005025126 and Pi-2 0.19597989949748743
mu-1 [0.96998989 1.02894917] and mu-2 [-1.02482819 -0.91492055]
sig-1 [[0.96127884 0.07824879]
[0.07824879 0.82105102]] and sig-2 [[1.1978678 0.48182629]
[0.48182629 0.93767199]]
| MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Visualize the likelihoodNow that you have the parameters, let us visualize how the likelihood looks like.1. Use $\texttt{np.mgrid}$ to generate points uniformly spaced in -5 to 5 along 2 axes1. Use $\texttt{multivariate_normal.pdf}$ to get compute the Gaussian likelihood for each class 1. Use $\texttt{plot_surface}$ ... | from matplotlib import cm
x,y = np.mgrid[-5:5:.01, -5:5:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
mu1 = calculate_mu_1()
mu2 = calculate_mu_2()
cov1 = calculate_cov_1()
cov2 = calculate_cov_2()
rv1 = multivariate_normal(mean = mu1, cov = cov1)
rv2 = multivariate_normal(mean = mu2, cov = c... | (160, 2)
(39, 2)
| MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Visualize the posteriorUse the prior and the likelihood you've computed to obtain the posterior distribution for each class.Like in the case of the likelihood above, make same similar surface and contour plots for the posterior. | likelihood1 = rv1.pdf(pos)
likelihood2 = rv2.pdf(pos)
p1 = (likelihood1 * pi1)/(likelihood1*pi1+likelihood2*pi2)
p2 = (likelihood2 * pi2)/(likelihood1*pi1+likelihood2*pi2)
x, y = np.mgrid[-5:5:.01, -5:5:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
fig = plt.figure(figsize=(20,10))
ax = fig.a... | _____no_output_____ | MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Decision boundary1. Decision boundary can be obtained by $P(C_2|x)>P(C_1|x)$ in python. Use $\texttt{contourf}$ to plot the decision boundary. Use $\texttt{cmap=cm.Blues}$ and $\texttt{alpha=0.5}$1. Also overlay the scatter plot of train data points from the 2 classes on the same plot. Use red color for class 1 and bl... | des = p2>p1
plt.contourf(x,y,p1,cmap=cm.Reds,alpha=0.5)
plt.contourf(x,y,p2,cmap=cm.Blues,alpha=0.5)
plt.contourf(x,y,des,cmap=cm.Greens,alpha=0.3)
plt.xlabel('x')
plt.ylabel('y')
plt.scatter(class1_train[:,0],class1_train[:,1],marker='*',color='red')
plt.scatter(class2_train[:,0],class2_train[:,1],marker='+',color='bl... | _____no_output_____ | MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Test DataNow let's use our trained model to classify test data points1. $\texttt{test_data}$ contains the $x1,x2$ features of different data points1. $\texttt{test_label}$ contains the true class of the data points. 0 means class 1. 1 means class 2. 1. Classify the test points based on whichever class has higher post... | test = pd.read_csv('https://raw.githubusercontent.com/shala2020/shala2020.github.io/master/Lecture_Materials/Assignments/MachineLearning/L3/test').to_numpy()
test_data, test_label = test[:,:2], test[:,2]
test_data
## likelihood
l1 = rv1.pdf(test_data)
l2 = rv2.pdf(test_data)
##Posterior
p1_test= (l1*pi1)/(l1*pi1+l2... | _____no_output_____ | MIT | 07-Assignment/Bayesian_Classifier_Assignment3_ML.ipynb | hritik5102/SHALA2020 |
Data Wrangling & Cleaning | # import the library
%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# convert scientific notation to decimals
pd.set_option('display.float_format', lambda x: '%.2f' % x) | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Load & Merge the data | df_listing = pd.read_csv('data/kc_house_data.csv')
df_walking_score = pd.read_csv('data/walking_score.csv')
df_income = pd.read_csv('data/ZIP-3.csv') | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Summarizing your data for inspection | print('Listings')
print(df_listing.columns)
print(df_listing.head())
print(df_listing.describe())
print('')
print('Walking Score')
# TODO: print the columns, head and describe for the Walking Score dataframe
print('')
print('Income')
# TODO: print the columns, head and describe for the Income dataframe | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Fixing column name | df_income.columns = ['zipcode', 'median_income', 'mean_income', 'population'] | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Converting data types | df_listing['date'] = pd.to_datetime(df_listing['date'])
df_income['median_income'] = df_income['median_income'].str.replace(',', '').astype(float)
df_income['mean_income'] = df_income['mean_income'].str.replace(',', '').astype(float)
df_income.head()
# TODO: Convert the data type of the population column
df_income | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Dealing with missing valuesHow to deal with the missing values? Should we remove the rows or fill the gap with a value? | # Number of missing values by columns
print(df_listing.isnull().sum())
print('')
print(df_walking_score.isnull().sum())
print('')
print(df_income.isnull().sum())
# select all the rows with missing values
df_walking_score[df_walking_score.isnull().any(axis=1)]
# select all the rows with missing values
df_income[df_incom... | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Removing outliersSome algorithms are very sensitive to outliers. Considering the number of bedrooms, should we remove houses with an extreme number of bedrooms? How many bedrooms are too many? (Suggestion: as a rule of thumb, three standard deviations from the mean is a good measure to identify outliers). | # bedrooms
print(df_listing['bedrooms'].value_counts())
print('mean', np.mean(df_listing['bedrooms']))
print('std', np.std(df_listing['bedrooms']))
plt.hist(df_listing['bedrooms'], bins=20)
plt.show()
# TODO: Remove the outlier houses considering the number of bedrooms
# Dealing with outliers
houses_to_remove = []
# r... | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Merging Data Sets | df_merge = df_listing.copy()
df_merge = df_merge.merge(df_walking_score, on='zipcode', how='left')
df_merge = df_merge.merge(df_income, on='zipcode', how='left')
print('Total # houses', len(df_merge)) | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Saving the processed file | df_merge.to_csv('data/house_pricing.csv', index=False) | _____no_output_____ | MIT | data-wrangling-analysis.ipynb | Clercy/proj_bedbugs |
Standalone Convergence Checker for the numerical vKdV solver KISSME bottom - KISSME stratificationGetting more realistic now. Using the real KISSME stratification. Still linear non hydrostaticStill using an offshore 'blank' zone with initial conditions not boundary conditions | import xarray as xr
from iwaves.kdv.kdvimex import KdVImEx#from_netcdf
from iwaves.kdv.vkdv import vKdV
from iwaves.kdv.solve import solve_kdv
from iwaves.utils.plot import vKdV_plot
import iwaves.utils.initial_conditions as ics
import iwaves.utils.boundary_conditions as bcs
import pandas as pd
import numpy as np
fro... |
Running dx=50
178852.84114035743
50
Calculating eigenfunctions...
0.0 % complete...
5.0 % complete...
10.0 % complete...
15.0 % complete...
20.0 % complete...
25.0 % complete...
30.0 % complete...
35.0 % complete...
40.0 % complete...
45.0 % complete...
50.0 % complete...
55.0 % complete...
60.0 % complete...
65.0 ... | BSD-2-Clause | tests/.ipynb_checkpoints/standalone_vkdv_convergence KISSME bathy REAL BVP-checkpoint.ipynb | iosonobert/iwaves |
Just double check that vKdV used the correct bathy | x, h, spongedist = get_kissme_h(50, kb_start)
# h = 0*x+d
plt.figure(figsize=(9,5))
plt.plot(x, h, 'b', label='Intended bathy', linewidth=2)
plt.plot(all_vkdv_dx_s[-1].x, all_vkdv_dx_s[-1].h, 'r--', label='Actual vKdV bathy')
plt.ylabel('h (m)')
plt.xlabel('x (m)')
plt.title('vKdV bathy')
plt.legend()
plt.show()
... | <ipython-input-91-3b71a6ddff0e>:5: UserWarning: Attempted to set non-positive left xlim on a log-scaled axis.
Invalid limit will be ignored.
plt.xlim(0,0.5e2)
<ipython-input-91-3b71a6ddff0e>:5: UserWarning: Attempted to set non-positive left xlim on a log-scaled axis.
Invalid limit will be ignored.
plt.xlim(0,0.5e2... | BSD-2-Clause | tests/.ipynb_checkpoints/standalone_vkdv_convergence KISSME bathy REAL BVP-checkpoint.ipynb | iosonobert/iwaves |
Copyright 2021 The TF-Agents 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/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
REINFORCE 代理 在 TensorFlow.org 上查看 在 Google Colab 运行 在 Github 上查看源代码 下载笔记本 简介 本例介绍如何使用 TF-Agents 库在 Cartpole 环境中训练 [REINFORCE](http://www-anw.cs.umass.edu/~barto/courses/cs687/williams92simple.pdf) 代理,与 [DQN 教程](1_dqn_tutorial.ipynb)比较相似。我们会引导您完成强化... | !sudo apt-get update
!sudo apt-get install -y xvfb ffmpeg freeglut3-dev
!pip install 'imageio==2.4.0'
!pip install pyvirtualdisplay
!pip install tf-agents[reverb]
!pip install pyglet xvfbwrapper
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
超参数 | env_name = "CartPole-v0" # @param {type:"string"}
num_iterations = 250 # @param {type:"integer"}
collect_episodes_per_iteration = 2 # @param {type:"integer"}
replay_buffer_capacity = 2000 # @param {type:"integer"}
fc_layer_params = (100,)
learning_rate = 1e-3 # @param {type:"number"}
log_interval = 25 # @param {type:... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
环境RL 环境用于描述要解决的任务或问题。在 TF-Agents 中,使用 `suites` 可以轻松创建标准环境。我们提供了不同的 `suites`,只需提供一个字符串环境名称,即可帮助您从来源加载环境,如 OpenAI Gym、Atari、DM Control 等。现在,我们试试从 OpenAI Gym 套件加载 CartPole 环境。 | env = suite_gym.load(env_name) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
我们可以渲染此环境以查看其形式:小车上连接一条自由摆动的长杆。目标是向右或向左移动小车,使长杆保持朝上。 | #@test {"skip": true}
env.reset()
PIL.Image.fromarray(env.render()) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
在该环境中,`time_step = environment.step(action)` 语句用于执行 `action`。返回的 `TimeStep` 元组包含该操作在环境中的下一个观测值和奖励。环境中的 `time_step_spec()` 和 `action_spec()` 方法分别返回 `time_step` 和 `action` 的规范(类型、形状、边界)。 | print('Observation Spec:')
print(env.time_step_spec().observation)
print('Action Spec:')
print(env.action_spec()) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
我们可以看到,该观测值是一个包含 4 个浮点数的数组:小车的位置和速度,长杆的角度位置和速度。由于只有两个操作(向左或向右移动),因此,`action_spec` 是一个标量,其中 0 表示“向左移动”,1 表示“向右移动”。 | time_step = env.reset()
print('Time step:')
print(time_step)
action = np.array(1, dtype=np.int32)
next_time_step = env.step(action)
print('Next time step:')
print(next_time_step) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
通常,我们会创建两个环境:一个用于训练,另一个用于评估。大部分环境都是使用纯 Python 语言编写的,但是使用 `TFPyEnvironment` 包装器可轻松将其转换至 TensorFlow 环境。原始环境的 API 使用 NumPy 数组,但凭借 `TFPyEnvironment`,这些数组可以与 `Tensors` 相互转换,从而更轻松地与 TensorFlow 策略和代理交互。 | train_py_env = suite_gym.load(env_name)
eval_py_env = suite_gym.load(env_name)
train_env = tf_py_environment.TFPyEnvironment(train_py_env)
eval_env = tf_py_environment.TFPyEnvironment(eval_py_env) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
代理我们用于解决 RL 问题的算法以 `Agent` 形式表示。除了 REINFORCE 代理,TF-Agents 还为各种 `Agents` 提供了标准实现,如 [DQN](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf)、[DDPG](https://arxiv.org/pdf/1509.02971.pdf)、[TD3](https://arxiv.org/pdf/1802.09477.pdf)、[PPO](https://arxiv.org/abs/1707.06347) 和 [SAC](https://arxiv.org/abs/18... | actor_net = actor_distribution_network.ActorDistributionNetwork(
train_env.observation_spec(),
train_env.action_spec(),
fc_layer_params=fc_layer_params) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
我们还需要一个 `optimizer` 来训练刚才创建的网络,以及一个跟踪网络更新次数的 `train_step_counter` 变量。 | optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
train_step_counter = tf.Variable(0)
tf_agent = reinforce_agent.ReinforceAgent(
train_env.time_step_spec(),
train_env.action_spec(),
actor_network=actor_net,
optimizer=optimizer,
normalize_returns=True,
train_step_counter=train_s... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
策略在 TF-Agents 中,策略是 RL 中的标准策略概念:给订 `time_step` 来产生操作或操作的分布。主要方法是 `policy_step = policy.step(time_step)`,其中 `policy_step` 是命名元祖 `PolicyStep(action, state, info)`。`policy_step.action` 是要应用到环境的 `action`,`state` 表示有状态 (RNN) 策略的状态,而 `info` 可能包含辅助信息(如操作的对数几率)。代理包含两个策略:一个是用于评估/部署的主要策略 (agent.policy),另一个是用于数据收集的策略 (agent.coll... | eval_policy = tf_agent.policy
collect_policy = tf_agent.collect_policy | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
指标和评估用于评估策略的最常用指标是平均回报。回报就是在环境中运行策略时,某个片段获得的奖励总和,我们通常会计算几个片段的平均值。计算平均回报指标的代码如下。 | #@test {"skip": true}
def compute_avg_return(environment, policy, num_episodes=10):
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while not time_step.is_last():
action_step = policy.action(time_step)
time_step = environment.step(acti... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
回放缓冲区为了跟踪从环境收集的数据,我们将使用 [Reverb](https://deepmind.com/research/open-source/Reverb),这是 Deepmind 打造的一款高效、可扩展且易于使用的回放系统。它会在我们收集轨迹时存储经验数据,并在训练期间使用。此回放缓冲区使用描述要存储的张量的规范进行构造,可以使用 `tf_agent.collect_data_spec` 从代理获取这些张量。 | table_name = 'uniform_table'
replay_buffer_signature = tensor_spec.from_spec(
tf_agent.collect_data_spec)
replay_buffer_signature = tensor_spec.add_outer_dim(
replay_buffer_signature)
table = reverb.Table(
table_name,
max_size=replay_buffer_capacity,
sampler=reverb.selectors.Uniform(),
remov... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
对于大多数代理,`collect_data_spec` 是一个 `Trajectory` 命名元组,其中包含观测值、操作和奖励等。 数据收集当 REINFORCE 从全部片段中学习时,我们使用给定数据收集策略定义一个函数来收集片段,并在回放缓冲区中将数据(观测值、操作、奖励等)保存为轨迹。这里我们使用“PyDriver”运行经验收集循环。您可以在我们的 [driver 教程](https://tensorflow.google.cn/agents/tutorials/4_drivers_tutorial)中了解到有关 TF Agents driver 的更多信息。 | #@test {"skip": true}
def collect_episode(environment, policy, num_episodes):
driver = py_driver.PyDriver(
environment,
py_tf_eager_policy.PyTFEagerPolicy(
policy, use_tf_function=True),
[rb_observer],
max_episodes=num_episodes)
initial_time_step = environment.reset()
driver.run(initial_ti... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
训练代理训练循环包括从环境收集数据和优化代理的网络。在训练过程中,我们偶尔会评估代理的策略,看看效果如何。运行下面的代码大约需要 3 分钟。 | #@test {"skip": true}
try:
%%time
except:
pass
# (Optional) Optimize by wrapping some of the code in a graph using TF function.
tf_agent.train = common.function(tf_agent.train)
# Reset the train step
tf_agent.train_step_counter.assign(0)
# Evaluate the agent's policy once before training.
avg_return = compute_av... | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
可视化 绘图我们可以通过绘制回报与全局步骤的图形来了解代理的性能。在 `Cartpole-v0` 中,长杆每停留一个时间步骤,环境就会提供一个 +1 的奖励,由于最大步骤数量为 200,所以可以获得的最大回报也是 200。 | #@test {"skip": true}
steps = range(0, num_iterations + 1, eval_interval)
plt.plot(steps, returns)
plt.ylabel('Average Return')
plt.xlabel('Step')
plt.ylim(top=250) | _____no_output_____ | Apache-2.0 | site/zh-cn/agents/tutorials/6_reinforce_tutorial.ipynb | RedContritio/docs-l10n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.