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 |
|---|---|---|---|---|---|
Data PreprocessingSince the majority of the machine learning models in the Sklearn library doesn't handle string category data and Null value, we have to explicitly remove or replace null values. The below snippet have functions, which removes the null value if any exists. And convert the string classes data in the da... | def NullClearner(df):
if(isinstance(df, pd.Series) and (df.dtype in ["float64","int64"])):
df.fillna(df.mean(),inplace=True)
return df
elif(isinstance(df, pd.Series)):
df.fillna(df.mode()[0],inplace=True)
return df
else:return df
def EncodeX(df):
return pd.get_dummies(df) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Calling preprocessing functions on the feature and target set. | x=X.columns.to_list()
for i in x:
X[i]=NullClearner(X[i])
X=EncodeX(X)
Y=NullClearner(Y)
X.head() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Correlation MapIn order to check the correlation between the features, we will plot a correlation matrix. It is effective in summarizing a large amount of data where the goal is to see patterns. | f,ax = plt.subplots(figsize=(18, 18))
matrix = np.triu(X.corr())
se.heatmap(X.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax, mask=matrix)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Data SplittingThe train-test split is a procedure for evaluating the performance of an algorithm. The procedure involves taking a dataset and dividing it into two subsets. The first subset is utilized to fit/train the model. The second subset is used for prediction. The main motive is to estimate the performance of th... | x_train,x_test,y_train,y_test=train_test_split(X,Y,test_size=0.2,random_state=123) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
ModelElastic Net first emerged as a result of critique on Lasso, whose variable selection can be too dependent on data and thus unstable. The solution is to combine the penalties of Ridge regression and Lasso to get the best of both worlds.Features of ElasticNet Regression-It combines the L1 and L2 approaches.It perfo... | model=make_pipeline(RobustScaler(), PowerTransformer(), ElasticNet())
model.fit(x_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.score: The score function returns the coefficient of determination R2 of the prediction. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100))
#prediction on testing set
prediction=model.predict(x_test) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Model evolutionr2_score: The r2_score function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions.MAE: The mean abosolute error function calculates the amount of total error(absolute average distance between the real data and the predicted data) by our m... | print('Mean Absolute Error:', mean_absolute_error(y_test, prediction))
print('Mean Squared Error:', mean_squared_error(y_test, prediction))
print('Root Mean Squared Error:', np.sqrt(mean_squared_error(y_test, prediction)))
print("R-squared score : ",r2_score(y_test, prediction)) | R-squared score : 0.7453424175665325
| Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(14,10))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(x_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/ElasticNet_RobustScaler_PowerTransformer.ipynb | shreepad-nade/ds-seed |
Pokemon Context Pokémon (ポケモン , Pokemon) és un dels videojocs que Satoshi Tajiri va crear per a diverses plataformes, especialment la Game Boy, i que gràcies a la seva popularitat va aconseguir expandir-se a altres mitjans d'entreteniment, com ara sèries de televisió, jocs de cartes i roba, convertint-se, així, en un... | import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
#conda install -c conda-forge missingno
import missingno as msno
import scipy as sp
path_folder = './datasets' | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Carregar les dades Pokemon_info dataset | pokemon_info_df = pd.read_csv(path_folder+'/pokemon.csv')
#Dimensions del DF (files, columnes)
print(pokemon_info_df.shape) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Hi ha **42 variables** i **801 registres**.Quins són els diferents tipus de variables? | print(pokemon_info_df.dtypes.unique()) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Hi ha variables de tipus: * ***O***: Categòrica.* ***float64***: Real.* ***int64***: Enter.De quin tipus és cada variable? | #Variables
print(pokemon_info_df.dtypes) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució del tipus de les variables. | pd.value_counts(pokemon_info_df.dtypes).plot.bar() | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Nota:** Com es pot veure, hi ha moltes variables de tipus ***float64*** i ***int64***, es probable que donat el domini d'aquestes variables, es pogués canviar el tipus a **float32** i **int32** per així reduir la quantitat de memòria utilitzada. Selecció de variablesA partir de les preguntes plantejades en el primer ... | pokemon_info_df = pokemon_info_df[["name","pokedex_number",\
"generation","type1","type2",\
"is_legendary","attack","sp_attack",\
"defense","sp_defense","speed",\
"hp","height_m","weight_kg",\
"against_bug","against_dark","against_drag... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
*pokemon_battles dataset* | pokemon_battles_df = pd.read_csv(path_folder+'/combats.csv')
print(pokemon_battles_df.shape) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Hi ha **38,743 registres** i **3 variables.**De quin tipus són? | print(pokemon_battles_df.dtypes.unique())
print(pokemon_battles_df.dtypes) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Nota:** Totes les variables són enteres (*int64*). Selecció de variablesEn aquest *dataset* són necessaries totes les variables, i per tant, no es fa cap selecció. --- [3] Neteja de les dadesUn cop es coneixen les variables de les quals es disposa per l'anàlisi i el seu tipus, és important explorar quines d'aquestes ... | #Hi ha algún camp en tot el DF que tingui un valor mancant?
print(pokemon_info_df.isnull().values.any()) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Valors mancantsQuins camps tenen valors mancants? | pokemon_info_mv_list = pokemon_info_df.columns[pokemon_info_df.isnull().any()].tolist()
print(pokemon_info_mv_list) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Les variables: **height_m**, **percentage_male**, **type2**, **weight_kg** tenen valors mancants, però quants registres estan afectats? | def missing_values(df, fields):
n_rows = df.shape[0]
for field in fields:
n_missing_values = df[field].isnull().sum()
print("%s: %d (%.3f)" % (field, n_missing_values, n_missing_values/n_rows))
msno.bar(pokemon_info_df[pokemon_info_mv_list], color="#b2ff54", labels=True) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com es distribueixen els valors mancants en funció de l'ordre del *Pokemon* imputat per la *Pokedex*? | msno.matrix(pokemon_info_df[pokemon_info_mv_list]) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
La variable **height_m** té 20 registres sense valor (2.5%), **type2** 384 (48%) i **weight_kg** 20 (2.5%) Imputar els valors perdutsPer tal d'imputar correctament els valors perduts, cal primer observar els altres valors per cada una d'aquestes variables. Així que anem a veure quins valors diferents hi ha per cada va... | print(pokemon_info_df[pokemon_info_df['type2'].notnull()]['type2'].unique()) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com es pot veure, hi ha 18 tipus de Pokemon diferents en la variable **type2**. **Com que es tracta d'una variable arbitraria definida pel dissenyador del *Pokemon*, no té cap sentit imputar un valor en base a la similitud que té amb els altres *Pokemons*, i per això, es decideix assignar l'etiqueta arbitrària (*unknow... | pokemon_info_df['type2'].fillna('unknown', inplace=True) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**height_m**Com que només hi ha un 20 registres sense valor per aquesta variable i el nombre de registres és molt superior a 50, es poden descartar. Per fer-ho assignem el valor 0, i així es remarca que la dada no existeix perquè no té sentit un *Pokemon* que no tingui alçada.**Nota:** En cas que el nombre de registres... | pokemon_info_df['height_m'].fillna(np.int(0), inplace=True) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**weight_kg**Igual que amb la variable **height_m** | pokemon_info_df['weight_kg'].fillna(np.int(0), inplace=True) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Ara es pot comprovar que no hi ha cap valor *na* en tot el *dataset* | print(pokemon_info_df.columns[pokemon_info_df.isnull().any()].tolist() == []) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Dades extremesLes dades extremes o *outliers* són aquelles que estàn fora del rang que es pot considerar normal per una variable numèrica. Hi ha diferents maneres de detectar les dades extremes, un dels més comuns és considerar com a tal a totes aquelles dades inferiors a *Q1* - 1.5 * *RIQ* o superior a *Q3* + 1.5 * *... | def print_min_max(var):
data = pokemon_info_df[var]
data = sorted(data)
q1, q2, q3 = np.percentile(data, [25,50,75])
iqr = q3 - q1
lower_bound = q1 - (1.5 * iqr)
upper_bound = q3 + (1.5 * iqr)
data_pd = pokemon_info_df[var]
outliers = data_pd[(data_pd < lower_bound) | (data_pd > upper_bo... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Una manera de representar aquesta informació és a través de diagrames de caixa o *boxplots* | plt.subplots(figsize=(15,10))
sns.boxplot(data=pokemon_info_df[['attack', 'sp_attack', 'defense', 'sp_defense', 'speed', \
'hp', 'weight_kg', 'height_m']], orient='v') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
De les variables analitzades, totes tenen relativament poques dades atípiques i les que en tenen no són molt pronunciats a excepció de la variable *weight_kg*, com que aquesta variable no s'usarà en la construcció del model predictiu, s'ha decidit assumir el risc de treballar amb les dades extremes i no eliminar-les de... | pokemon_info_df.to_csv(path_folder+'/pokemon_clean_data.csv') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
[4, 5]. Anàlisi descriptiu GeneracionsQuantes generacions hi ha? | print("Hi ha %d generacions de Pokemons" %(pokemon_info_df["generation"].nunique())) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució dels *Pokemons* en base a la generacióCom es distribueixen els Pokemons en base a la primera generació en que van apareixre? | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
#Diagrama de barres
sns.countplot(x="generation", data=pokemon_info_df, ax=ax1)
#Diagrama de sectors
sector_diagram = pd.value_counts(pokemon_info_df.generation)
sector_diagram.plot.pie(startangle=90, autopct='%1.1f%%', shadow=False,
explo... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Quines són les tres generacions on van apareixer més Pokemons? | print("5na generació -> %d Pokemons"%(len(pokemon_info_df[pokemon_info_df["generation"] == 5])))
print("1ra generació -> %d Pokemons"%(len(pokemon_info_df[pokemon_info_df["generation"] == 1])))
print("3era generació -> %d Pokemons"%(len(pokemon_info_df[pokemon_info_df["generation"] == 3]))) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
La generació amb més Pokemons és la **5na** amb **156 (19,5%)**, seguidament de la **1era** generació amb **151 (18,9%)** i finalment la **3era** generació amb **135 Pokemons (16,9%)**. Entre aquestes tres generacions hi ha el **55,3%** del total de *Pokemons*. Pokemons llegendarisHi ha *Pokemons* que despunten per so... | print("Nombre total de Pokemons llegendaris: {}".format(len(pokemon_info_df[pokemon_info_df["is_legendary"] == True]))) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
En total hi ha **70 Pokemons llegendaris.** Distribució dels *Pokemons* llegendarisEn quines edicions apareixen aquests Pokemons? | pokemon_legendary_df = pokemon_info_df[pokemon_info_df["is_legendary"] == True]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
#Diagrama de barres
sns.countplot(x="generation", data=pokemon_legendary_df, ax=ax1)
#Diagrama de sectors
sector_diagram = pd.value_counts(pokemon_legendary_df.generation)
sector_diagr... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
La **7na generació** té **17 Pokemons llegendaris (24,3%)**, la **4rta** en té **13 (18,6%)** i la **5na 13**. Entre **aquestes tres generacions** hi ha un **61,5% de Pokemons llegendaris**. Tipus dels *Pokemons* llegendarisQuin són els tipus (*type1* i *type2*) que predominen en els *Pokemons* llegendaris? | def plot_by_type(dataFrame, title):
plt.subplots(figsize=(15, 13))
sns.heatmap(
dataFrame[dataFrame["type2"] != "unknown"].groupby(["type1", "type2"]).size().unstack(),
cmap="Blues",
linewidths=1,
annot=True
)
plt.xticks(rotation=35)
plt.title(title)
plt.show()
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Els tipus **psíquic/fantasma**, **foc/volador**, **elèctric/volador**, **insecte/lluita** i **drac/psíquic** són els tipus amb més *Pokemons* llegendaris, tots ells amb 2 exemplars. *Pokemon* llegendari més fortQuin és el Pokemon llegendari amb més atac (attack), defensa (defense), vida (hp) i velocitat (velocity) mitj... | legendary_with_more_attack = max(pokemon_legendary_df['attack'])
legendary_with_less_attack = min(pokemon_legendary_df['attack'])
legendary_with_more_defense = max(pokemon_legendary_df['defense'])
legendary_with_less_defense = min(pokemon_legendary_df['defense'])
legendary_with_more_hp = max(pokemon_legendary_df['hp'... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
En base al càlcul realitzat, podem considerar que el *Pokemon* llegendari més fort és **Groudon** amb una ponderació de: 2,44 punts i el més dèbil és **Cosmog** amb una ponderació de 0 punts. *Type1* i *type2*Cada *Pokemon* és d'un tipus concret **type1** o és una combinació de **type1** i **type2**, per aquest motiu,... | single_type_pokemons = []
dual_type_pokemons = []
for i in pokemon_info_df.index:
if(pokemon_info_df.type2[i] != "unknown"):
single_type_pokemons.append(pokemon_info_df.name[i])
else:
dual_type_pokemons.append(pokemon_info_df.name[i])
print("Nombre de Pokemons amb un únic tipus %d: " %... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Hi ha **417** d'un únic tipus (**52,1%**) i **384** amb doble tipus (**47,9%**), això es representa en el següent diagrama de sectors. | data= [len(single_type_pokemons), len(dual_type_pokemons)]
colors= ["#ced1ff","#76bfd4"]
plt.pie(data, labels=["Tipus únic","Doble tipus"],
startangle=90, explode=(0, 0.15),
shadow=True, colors=colors, autopct='%1.1f%%')
plt.axis("equal")
plt.title("Tipus únic vs Doble tipus")
plt.tight_layout()
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució en base al tipusEn els següents diagrames de barres es mostra la distribució per **type1** i per **type2** | def plot_distribution(data, col, xlabel, ylabel, title):
types = pd.value_counts(data[col])
fig, ax = plt.subplots()
fig.set_size_inches(15,7)
sns.set_style("whitegrid")
ax = sns.barplot(x=types.index, y=types, data=data)
ax.set_xticklabels(ax.get_xticklabels(), rotation=75, fontsize=12)
a... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Combinació de tipusAra volem saber quina combinació de tipus **type1** i **type2** hi ha entre tots els Pokemons. | plt.subplots(figsize=(15, 13))
sns.heatmap(
pokemon_info_df[pokemon_info_df["type2"] != "unknown"].groupby(["type1", "type2"]).size().unstack(),
cmap="Blues",
linewidths=1,
annot=True
)
plt.xticks(rotation=35)
plt.show() | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com es pot veure, la combinació de tipus més comuna és **normal/volador** amb **26 Pokemons** seguida per la combinació **planta/verí** i **insecte/volador** amb **14** i **13 Pokemons** respectivament.**Nota:** En aquest mapa de calor s'han filtrat tots aquells Pokemons sense segon tipus. Pes i alçadaLa variable **he... | tallest_m = max(pokemon_info_df['height_m'])
shortest_m = tallest_m
for i in pokemon_info_df.index:
if pokemon_info_df.height_m[i] > 0 and pokemon_info_df.height_m[i] < shortest_m:
shortest_m = pokemon_info_df.height_m[i]
tallest_pokemon = pokemon_info_df[pokemon_info_df['height_m'] == tallest_m]
shortest_... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució de l'alçada i del pesAra es vol veure quina és la distribució de l'alçada i pes dels Pokemons, per això es pot utilitzar histogrames i diagrames de caixa. | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15,5))
sns.distplot(pokemon_info_df['height_m'], color='g', axlabel="Alçada (m)", ax=ax1)
sns.distplot(pokemon_info_df['weight_kg'], color='y', axlabel="Pes (kg)", ax=ax2)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
sns.boxplot(x=pokemon_info_df["height_m"], col... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Tots aquells Pokemons amb una alçada inferior a Com es pot veure, hi ha Pokemons molt dispersos a la resta, es con VelocitatQuins són els *Pokemons* més ràpids i quins els més lents? | fast_value = max(pokemon_info_df['speed'])
slow_value = min(pokemon_info_df[pokemon_info_df['speed'] != 0]['speed'])
fastest_pokemon = pokemon_info_df[pokemon_info_df['speed'] == max(pokemon_info_df['speed'])]
slowest_pokemon = pokemon_info_df[pokemon_info_df['speed'] == slow_value]
print("Els Pokemons més ràpids són... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució de la velocitat | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
sns.distplot(pokemon_info_df['speed'], color="orange", ax=ax1)
sns.boxplot(pokemon_info_df['speed'], color="orange", orient="v", ax=ax2) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Atac i defensaEn els següents gràfics es comparen: l'atac i l'atac especial base, la defensa i la defensa especial base. | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
sns.distplot(pokemon_info_df['attack'], color="#B8F0FC", hist=False, ax=ax1, label="Attack")
sns.distplot(pokemon_info_df["sp_attack"], color="#52BAD0", hist=False, ax=ax1, label="S. Attack")
ax1.title.set_text("Attack vs Special Attack")
ax2.title.set_text("Defen... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
En els següents gràfics es comparen: l'atac i la defensa base, l'atac especial i la defensa especial base. | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
ax1.title.set_text("Attack vs Defense")
sns.distplot(pokemon_info_df['attack'], color="#B8F0FC", hist=False, ax=ax1, label="Attack")
sns.distplot(pokemon_info_df["defense"], color="#52BAD0", hist=False, ax=ax1, label="Defense")
ax2.title.set_text("Special Attack v... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
[4]. Distribució de les variablesEn aquest apartat s'estudiarà la distribució que segueixen algunes de les variables i s'aplicaran contrastos de hipòtesi amb la finalitat d'extreure conclusions en base al tipus dels Pokemons.S'ha decidit estudiar les variables *atac*, *hp*, *defensa* i *velocitat*. Normalitat en la d... | sp.stats.shapiro(pokemon_info_df['attack'].to_numpy())
sp.stats.shapiro(pokemon_info_df['hp'].to_numpy())
sp.stats.shapiro(pokemon_info_df['defense'].to_numpy())
sp.stats.shapiro(pokemon_info_df['speed'].to_numpy())
sp.stats.shapiro(pokemon_info_df['height_m'].to_numpy())
sp.stats.shapiro(pokemon_info_df['weight_kg'].t... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Els testos per les variables *attack*, *hp*, *defense*, *speed*, *height_m* i *weight_kg* han obtingut un *p-value* inferior al nivell de significació ($\alpha$ = 0.05), i per tant hi ha evidències estadístqiues suficients per rebutjar la hipòtesi nul·la i acceptar que no segueixen una distribució normal. Homocedastici... | rock_pokemons_array = pokemon_info_df[(pokemon_info_df['type1'] == 'rock') \
& (pokemon_info_df['weight_kg'] != 0)]['weight_kg'].to_numpy()
fire_pokemons_array = pokemon_info_df[(pokemon_info_df['type1'] == 'fire') \
& (pokemon_info_df['weight_k... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com que s'ha obtingut un ***p-value*** de **0,044** (0,044 < $\alpha$), **hi ha suficients evidències estadístiques per rebutjar la hipótesi nul·la**, i per tant, s'accepta amb un **nivell de confiança del 95%** que **hi ha diferències entre les variancies dels Pokemons de tipus roca i els de tipus foc.** Contrast - Pe... | sp.stats.ttest_ind(a = rock_pokemons_array, b = fire_pokemons_array) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com que s'ha obtingut un ***p-value*** de **0,137**, **no hi ha evidències estadístiques suficients per rebutjar la hipòtesi nul·la**, i per tant **es pot considerar que la mitja de pes entre els Pokemons de tipus roca i de tipus foc és el mateix.** [4, 5] Anàlisi predictiuEn aquest punt **es dona per finalitzat l'anàl... | pokemon_battles_df | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
El primer que cal fer es relacionar el *dataset* que conté la informació dels Pokemons (*pokemon_info_df*) amb el *dataset* dels combats (*pokemon_battles_df*). Per això apliquem dos *joins*, el primer que relaciona aquests dos datasets per obtenir les dades del primer Pokemon i el segon *join* on es tornen a relaciona... | pokemon_battles_info_df = pokemon_battles_df.merge(pokemon_info_df, \
left_on='First_pokemon', \
right_on='pokedex_number' \
).merge(pokemon_info_df, \
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
El *dataset* resultant conté per nom *field_x* el resultat del primer join i *field_y* pel resultat del segon join. Apliquem un *rename* perquè els camps *field_x* començin per *First_pokemon* i els camps *field_y* per *Second_pokemon* | pokemon_battles_info_df.rename(columns={'name_x': 'First_pokemon_name', 'attack_x': 'First_pokemon_attack', \
'sp_attack_x': 'First_pokemon_sp_attack', 'defense_x': 'First_pokemon_defense', \
'sp_defense_x': 'First_pokemon_sp_defense', 'hp_... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Camps *diff_?*Per construir el model predictiu cal calcular els camps amb les diferències entre les propietats implicades. Aquestes s'anomenaran *Diff_?*. Per exemple, la diferència d'atac seria: *Diff_attack* = *First_pokemon_attack* - *Second_pokemon_attack* | pokemon_battles_info_df['Diff_attack'] = pokemon_battles_info_df['First_pokemon_attack'] - pokemon_battles_info_df['Second_pokemon_attack']
pokemon_battles_info_df['Diff_sp_attack'] = pokemon_battles_info_df['First_pokemon_sp_attack'] - pokemon_battles_info_df['Second_pokemon_sp_attack']
pokemon_battles_info_df['Diff... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Camp *winner_result*Com que l'objectiu d'aquest model predictiu és fer una classificació on el resultat sigui 0 si guanya el primer *Pokemon* o 1 en cas contrari. Afegim el camp ***Winner_result*** amb aquest càlcul. | pokemon_battles_info_df['Winner_result'] = np.where(\
pokemon_battles_info_df['First_pokemon'] == \
pokemon_battles_info_df['Winner'], 0, 1) | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Seleccionar els camps del modelAra creem el *dataset* ***pokemon_battles_pred_df*** amb els camps que s'usaran com a predictors, que són: * ***Diff_attack**** ***Diff_sp_attack**** ***Diff_defense**** ***Diff_sp_defense**** ***Diff_hp**** ***Diff_speed**** ***First_pokemon_is_legendary**** ***Second_pokemon_is_legenda... | pokemon_battles_pred = pokemon_battles_info_df[['Diff_attack', 'Diff_sp_attack', \
'Diff_defense', 'Diff_sp_defense', \
'Diff_hp', 'Diff_speed', \
'First_pokemon_is_legendary',... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Escalar les dadesSi els rangs de valors per les variables utilitzades en el model és considerablment diferent, poden causar distorsions en els resultats obtinguts. Per mostrar la seva distribució es pot utilitzar un *boxplot*. | plt.subplots(figsize=(15,10))
sns.boxplot(data=pokemon_battles_pred[:,0:6], orient='v') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Com es pot observar hi ha diferència entre el rang de les dades, per això es pot aplicar un escalat robust. | from sklearn.preprocessing import RobustScaler
rs = RobustScaler()
rs.fit(pokemon_battles_pred)
pokemon_battles_pred = rs.transform(pokemon_battles_pred)
plt.subplots(figsize=(15,10))
sns.boxplot(data=pokemon_battles_pred[:,0:6], orient='v') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Separar les dades en *dades d'entrenament* i *dades de prova*Com que és un **model supervisat**, cal separar les dades en dades d'entrenament i dades de prova. El model utilitzarà les dades d'entrenament per aprendre (fase d'entrenament) i les dades de prova per comprovar si el que ha aprés és o no correcte (fase de t... | from sklearn.model_selection import train_test_split
#S'ha decidit assignar el valor 23 a la llavor per així obtenir sempre el mateix resultat.
pokemon_battle_pred_train, pokemon_battle_pred_test, \
pokemon_battle_res_train, pokemon_battle_res_test = train_test_split(\
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Crear el model de regressió logística | from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression(random_state = 0)
classifier.fit(pokemon_battle_pred_train, pokemon_battle_res_train)
pokemon_battle_results = classifier.predict(pokemon_battle_pred_test)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(pokemon_battl... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 87,97% K nearest Neighbours (*Knn*) | from sklearn.neighbors import KNeighborsClassifier
knn_classifier = KNeighborsClassifier(n_neighbors=5, metric='minkowski', p=2)
knn_classifier.fit(X=pokemon_battle_pred_train, y=pokemon_battle_res_train)
knn_pokemon_battle_results = knn_classifier.predict(pokemon_battle_pred_test)
knn_cm = confusion_matrix(pokemon_bat... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 87,58% Support Vector Machine - SVM | from sklearn.svm import SVC
svm_classifier = SVC(kernel='rbf', random_state=0)
svm_classifier = svm_classifier.fit(X=pokemon_battle_pred_train, y=pokemon_battle_res_train)
svm_pokemon_battle_results = svm_classifier.predict(X=pokemon_battle_pred_test)
svm_cm = confusion_matrix(pokemon_battle_res_test, svm_pokemon_battl... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 90,92% Classificació per xarxa bayesiana (*Naive bayes*) | from sklearn.naive_bayes import GaussianNB
nb_classifier = GaussianNB()
nb_classifier = nb_classifier.fit(X=pokemon_battle_pred_train, y=pokemon_battle_res_train)
nb_pokemon_battle_results = nb_classifier.predict(X=pokemon_battle_pred_test)
nb_cm = confusion_matrix(pokemon_battle_res_test, nb_pokemon_battle_results)
pr... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 79,95% Random Forest Classifier (RFC) | from sklearn.ensemble import RandomForestClassifier
rfc_classifier = RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0)
rfc_classifier = rfc_classifier.fit(X=pokemon_battle_pred_train, y=pokemon_battle_res_train)
rfc_pokemon_battle_results = rfc_classifier.predict(X=pokemon_battle_pred_test)
r... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 92,25 Millor modelEl model que ha obtingut un millor *accuracy* ha estat el *Random Forest Classifier* amb un encert del 92,51%: Millorar el model (afegir el tipus dels *Pokemons*)Com s'ha mostrat en apartats anteriors, **cada *Pokemon* té un tipus base** i pot tenir un segon tipus. Evidentment, aquestes... | def effectivity_against(pokemon1, pokemon2, effectivity_type1, effectivity_type2):
type1 = pokemon1['type1'].iloc[0]
type2 = pokemon1['type2'].iloc[0]
against_type1 = pokemon2['against_'+type1].iloc[0]
if type2 == 'unknown':
return against_type1 * effectivity_type1
else:
against_type... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Ara cal afegir la propietat *balance_effectivity* al *dataframe pokemon_battles_info_df* | pokemon_battles_info_df['balance_effectivity'] = [\
balance_effectivity_against_by_pokedex_number(\
row['First_pokemon'], \
row['Second_pokemon']) \
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
S'afegeix la columna *balance_effectivity* al *dataframe pokemon_battles_pred* | pokemon_battles_improved_pred = pokemon_battles_info_df[['Diff_attack', 'Diff_sp_attack', \
'Diff_defense', 'Diff_sp_defense', \
'Diff_hp', 'Diff_speed', \
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Distribució de les variables | plt.subplots(figsize=(15,10))
sns.boxplot(data=pokemon_battles_improved_pred[:,[0,1,2,3,4,5,8]], orient='v') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Es normalitzen altre vegada les variables numèriques. | rs = RobustScaler()
rs.fit(pokemon_battles_improved_pred)
pokemon_battles_improved_pred = rs.transform(pokemon_battles_improved_pred)
plt.subplots(figsize=(15,10))
sns.boxplot(data=pokemon_battles_improved_pred[:,[0,1,2,3,4,5,8]], orient='v') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Un cop escalades, tornem a separar-les en un conjunt d'entrenament i un de prova. | pokemon_battles_improved_pred_train, pokemon_battles_improved_pred_test, \
pokemon_battles_improved_res_train, pokemon_battles_improved_res_test = train_test_split(\
pokemon_battles_improved_pred, \
... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
*Random forest* milloratCalculat l'atribut *balance_effectivity* que té en compte el tipus dels Pokemons involucrats en el combat, tornem a crear el model basat en *random forest* (ja que és amb el que hem obtingut un major *accuracy*) per veure si millorem els resultats. | improved_rfc_classifier = RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0)
improved_rfc_classifier = improved_rfc_classifier.fit(\
X=pokemon_battles_improved_pred_train, \
y=pokemon_ba... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
**Accuracy:** 92,56%**Nota:** Afegint la variable *balance_effectivity* augmenta la complexitat del model i millora l'accuracy només en un 0,31%. [Corba ROC](https://en.wikipedia.org/wiki/Receiver_operating_characteristic)La corba característica pel model obtingut és: | from sklearn.metrics import roc_curve, auc
fpr, tpr, _ = roc_curve(y_true=pokemon_battles_improved_res_test , y_score=improved_rfc_pokemon_battle_results)
auc = auc(fpr, tpr)
plt.subplots(figsize=(15, 8))
plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % auc)
plt.plot([0, 1], [0, 1], colo... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Torneig *Pokemon*Per comprovar l'efectivitat del model de predicció creat s'ha decidit realitzar un Torneig *Pokemon*, on hi participen **16 *Pokemons***, **8** dels quals **són llegendaris**. El Torneig consta de **8 combats** dividits en **4 fases**. | # Construeix les dades del combat que enfronta el pokemon1 contra el pokemon2,
#les dades retornades ja estan normalitzades.
def build_fight(name_pokemon1, name_pokemon2):
pokemon1 = pokemon_info_df[pokemon_info_df['name'] == name_pokemon1].iloc[0]
pokemon2 = pokemon_info_df[pokemon_info_df['name'] == name_pok... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Round 1 | fight1 = fight(classifier=improved_rfc_classifier, name_pokemon1='Snorlax', name_pokemon2='Ninetales')
fight2 = fight(classifier=improved_rfc_classifier, name_pokemon1='Gengar', name_pokemon2='Altaria')
fight3 = fight(classifier=improved_rfc_classifier, name_pokemon1='Raikou', name_pokemon2='Mew')
fight4 = fight(classi... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Round 2 | fight9 = fight(classifier=improved_rfc_classifier, name_pokemon1='Snorlax', name_pokemon2='Raikou')
fight10 = fight(classifier=improved_rfc_classifier, name_pokemon1='Altaria', name_pokemon2='Kommo-o')
fight11 = fight(classifier=improved_rfc_classifier, name_pokemon1='Swampert', name_pokemon2='Mewtwo')
fight12 = fight(... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Round 3 | fight9 = fight(classifier=improved_rfc_classifier, name_pokemon1='Snorlax', name_pokemon2='Mewtwo')
fight10 = fight(classifier=improved_rfc_classifier, name_pokemon1='Kommo-o', name_pokemon2='Arceus') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
Round 4 | fight10 = fight(classifier=improved_rfc_classifier, name_pokemon1='Mewtwo', name_pokemon2='Arceus') | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/data_analysis-checkpoint.ipynb | ogalera-dev/data-analysis |
import matplotlib.pyplot as plt
import numpy as np
plt.plot([2,4,6,8,10])
plt.show()
#plotting with lists
%matplotlib inline
plt.plot([2,5,9,7],[2,1,3,5], color='green', marker='o') #number of x points should be equal to number of y points
plt.xlabel('Bombs')
plt.ylabel('People')
plt.xlim(-5,20)
plt.ylim(0,20)
plt.sho... | _____no_output_____ | MIT | Tutorial 4/Tutorial_4_Plotting.ipynb | drkndl/IITB-Astro-Tutorials | |
Aliasing e o teorema da amostragemNeste notebook exploramos questões a respeito da taxa de amostragem. | # importar as bibliotecas necessárias
import numpy as np # arrays
import matplotlib.pyplot as plt # plots
plt.rcParams.update({'font.size': 14}) | _____no_output_____ | CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
Exemplo 1 Vamos criar um seno, entre 0 [s] e 1[s], com frequência 10 [Hz]. Vamos variar a taxa de amostragem e averiguar o que ocorre. | Fs = 15.7
time = np.arange(0, 1, 1/Fs)
xt = np.sin(2*np.pi*10*time)
N = len(xt) # Num. de amostras no sinal | _____no_output_____ | CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
1 período do espectroVamos calcular o espectro com a FFT e plotar 1 período de espectro. Note que o vetor de frequências vai de 0 até bem perto de $F_s$.A princípio, o espectro tem o mesmo número de amostras do sinal. | Xw = np.fft.fft(xt) # A princípio, o espectro tem o mesmo número de amostras do sinal
freq = np.linspace(0, (N-1)*Fs/Fs, N) # 1 período do vetor de frequências vai de 0 até bem perto de Fs.
print("xt possui {} amostras e Xw possui {} componentes de frequência".format(N, len(Xw)))
plt.figure()
plt.plot(freq, np.abs(Xw)... | xt possui 16 amostras e Xw possui 16 componentes de frequência
| CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
Vários período do espectro | # novo vetor de frequências - 3 períodos
plt.figure()
plt.plot(freq-Fs, np.abs(Xw)/N, '--b', linewidth = 2)
plt.plot(freq, np.abs(Xw)/N, 'b', linewidth = 2)
plt.plot(freq+Fs, np.abs(Xw)/N, '--b', linewidth = 2)
plt.axvline(Fs/2, color='k',linestyle = '--', linewidth = 4, alpha = 0.8)
plt.xlabel('Frequência [Hz]')
plt.y... | _____no_output_____ | CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
Exemplo 2 - Vamos ouvir um seno com várias taxas de amostragem | import IPython.display as ipd
from scipy import signal
# Gerar sinal com uma taxa de amostragem
fs = 1800
t = np.arange(0, 1, 1/fs) # vetor temporal
freq = 1000
w = 2*np.pi*freq
xt = np.sin(w*t)
# Reamostrar o sinal para a placa de som conseguir tocá-lo
fs_audio = 44100
xt_play = signal.resample(xt, fs_audio)
ipd.Aud... | _____no_output_____ | CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
Exemplo 3. Um sinal com 3 senos | Fs=100
T=2.0;
t=np.arange(0,T,1/Fs)
# 3 sinais com diferentes frequências
f1=10
f2=40
f3=80 #80 e 120
x1=np.sin(2*np.pi*f1*t)
x2=np.sin(2*np.pi*f2*t)
x3=0.2*np.sin(2*np.pi*f3*t)
# FFT
N=len(t)
X1=np.fft.fft(x1)
X2=np.fft.fft(x2)
X3=np.fft.fft(x3)
freq = np.linspace(0, (N-1)*Fs/N, N)
plt.figure(figsize=(8,20))
plt... | _____no_output_____ | CC0-1.0 | Aula 39 - Aliasing e solucoes/Amostragem 2.ipynb | RicardoGMSilveira/codes_proc_de_sinais |
Programming LSTM with Keras and TensorFlowSo far, the neural networks that we’ve examined have always had forward connections. Neural networks of this type always begin with an input layer connected to the first hidden layer. Each hidden layer always connects to the next hidden layer. The final hidden layer always c... | %matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import math
def sigmoid(x):
a = []
for item in x:
a.append(1/(1+math.exp(-item)))
return a
def f2(x):
a = []
for item in x:
a.append(math.tanh(item))
return a
x = np.arange(-10., 10., 0.2)... | Sigmoid
| Apache-2.0 | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA |
Both of these two functions compress their output to a specific range. For the sigmoid function, this range is 0 to 1. For the hyperbolic tangent function, this range is -1 to 1.LSTM maintains an internal state and produces an output. The following diagram shows an LSTM unit over three time slices: the current time ... | from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding
from tensorflow.keras.layers import LSTM
import numpy as np
max_features = 4 # 0,1,2,3 (total of 4)
x = [
[[0],[1],[1],[0],[0],[0]],
[[0],[0],[0],[2],[2],[0]],... | 1
| Apache-2.0 | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA |
Sun Spots ExampleIn this section, we see an example of RNN regression to predict sunspots. You can find the data files needed for this example at the following location.* [Sunspot Data Files](http://www.sidc.be/silso/datafilestotal)* [Download Daily Sunspots](http://www.sidc.be/silso/INFO/sndtotcsv.php) - 1/1/1818 to... | import pandas as pd
import os
# Replacce the following path with your own file. It can be downloaded from:
# http://www.sidc.be/silso/INFO/sndtotcsv.php
if COLAB:
PATH = "/content/drive/My Drive/Colab Notebooks/data/"
else:
PATH = "./data/"
filename = os.path.join(PATH,"SN_d_tot_V2.0.csv")
names = ['... | Starting file:
year month day dec_year sn_value sn_error obs_num
0 1818 1 1 1818.001 -1 NaN 0
1 1818 1 2 1818.004 -1 NaN 0
2 1818 1 3 1818.007 -1 NaN 0
3 1818 1 4 1818.010 -1 NaN 0
4 1818 ... | Apache-2.0 | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA |
As you can see, there is quite a bit of missing data near the end of the file. We want to find the starting index where the missing data no longer occurs. This technique is somewhat sloppy; it would be better to find a use for the data between missing values. However, the point of this example is to show how to use ... | start_id = max(df[df['obs_num'] == 0].index.tolist())+1 # Find the last zero and move one beyond
print(start_id)
df = df[start_id:] # Trim the rows that have missing observations
df['sn_value'] = df['sn_value'].astype(float)
df_train = df[df['year']<2000]
df_test = df[df['year']>=2000]
spots_train = df_train['sn_valu... | Build model...
Train...
Train on 55150 samples, validate on 7295 samples
Epoch 1/1000
55150/55150 - 13s - loss: 1312.6864 - val_loss: 190.2033
Epoch 2/1000
55150/55150 - 8s - loss: 513.1618 - val_loss: 188.5868
Epoch 3/1000
55150/55150 - 8s - loss: 510.8469 - val_loss: 191.0815
Epoch 4/1000
55150/55150 - 8s - loss: 506... | Apache-2.0 | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA |
Finally, we evaluate the model with RMSE. | from sklearn import metrics
pred = model.predict(x_test)
score = np.sqrt(metrics.mean_squared_error(pred,y_test))
print("Score (RMSE): {}".format(score)) | Score (RMSE): 13.732691339581104
| Apache-2.0 | Clase8-RNN/extras/2lstm.ipynb | diegostaPy/cursoIA |
Import Module | from random import random,randint,choice
import genetic as g | _____no_output_____ | MIT | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox |
Build Dataset | def hiddenfunction(x,y):
return x**2+2*y + 7
def buildhiddenset():
rows=[]
for i in range(200):
x=randint(0,40)
y=randint(0,40)
rows.append([x,y,hiddenfunction(x,y)])
return rows
hiddenset=buildhiddenset()
help(g.evolve) | Help on function evolve in module genetic:
evolve(pc, popsize, rankfunction, maxgen=500, mutationrate=0.1, breedingrate=0.4, pexp=0.7, pnew=0.05)
rankfunction
The function used on the list of programs to rank them from best to worst.
mutationrate
The probability of a mutation, passed on to muta... | MIT | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox |
Evolution | rank_func=g.getrankfunction(buildhiddenset())
best = g.evolve(2,500,rank_func,mutationrate=0.2,breedingrate=0.2,pexp=0.7,pnew=0.3)
best.display() | add
add
if
add
p1
8
add
if
1
subtract
7
subtract
7
add
p1
subtract
3
4
p0
8
add
if
if
isgreater
2
subtract
add
5
1
p0
isgreater
... | MIT | models/genetic_programming/example.ipynb | shawlu95/Data_Science_Toolbox |
SUPPORT VECTOR REGRESSIONSupport Vector Regression(SVR) adalah teknik Supervised Learning yang mengadopsi teknik Support Vector Machine(SVM). Yang membedakan adalah SVR menggunakan hyperplane sebagai dasar untuk membuat margin dan garis pembatas.Apakah yang membedakan SVR dengan regresi linear?Pada regresi linear, kit... | import numpy as np #aljabar linear
import pandas as pd #pengolahan data
import matplotlib.pyplot as plt #visualisasi
import warnings
warnings.filterwarnings("ignore")
df = pd.read_csv('salary.csv') #membaca data
df.head(10)
#mengubah data menjadi array agar bisa dilakukan proses machine learning
X = df.pengalaman.value... | _____no_output_____ | MIT | 2 Regression/2.3 support vector regression/SVR.ipynb | jordihasianta/DS_Kitchen |
Visualisasi | # data latih
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_grid, model.predict(X_grid), color = 'blue')
plt.title('Gaji vs Pengalaman (Training Set)')
plt.xlabel('pengalaman')
plt.ylabel('gaji')
plt.show()
#data uji
X_grid = np... | _____no_output_____ | MIT | 2 Regression/2.3 support vector regression/SVR.ipynb | jordihasianta/DS_Kitchen |
phageParser - Distribution of Number of Spacers per Locus C.K. Yildirim (cemyildirim@fastmail.com)The latest version of this [IPython notebook](http://ipython.org/notebook.html) demo is available at [http://github.com/phageParser/phageParser](https://github.com/phageParser/phageParser/tree/django-dev/demos)To run this... | # import packages
import requests
import json
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib import mlab
import seaborn as sns
import pandas as pd
from scipy import stats
sns.set_palette("husl")
#Url of the phageParser API
apiurl = 'https://phageparser.herokuapp.com'
#Get the initial p... | _____no_output_____ | MIT | demos/Locus Number of Spacers Analysis.ipynb | nataliyah123/phageParser |
Your first neural networkIn this project, you'll build your first neural network and use it to predict daily bike rental ridership. We've provided some of the code, but left the implementation of the neural network up to you (for the most part). After you've submitted this project, feel free to explore the data and th... | %matplotlib inline
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'retina'
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Load and prepare the dataA critical step in working with neural networks is preparing the data correctly. Variables on different scales make it difficult for the network to efficiently learn the correct weights. Below, we've written the code to load and prepare the data. You'll learn more about this soon! | data_path = 'Bike-Sharing-Dataset/hour.csv'
rides = pd.read_csv(data_path)
rides.head() | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Checking out the dataThis dataset has the number of riders for each hour of each day from January 1 2011 to December 31 2012. The number of riders is split between casual and registered, summed up in the `cnt` column. You can see the first few rows of the data above.Below is a plot showing the number of bike riders ov... | rides[:24*10].plot(x='dteday', y='cnt') | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Dummy variablesHere we have some categorical variables like season, weather, month. To include these in our model, we'll need to make binary dummy variables. This is simple to do with Pandas thanks to `get_dummies()`. | dummy_fields = ['season', 'weathersit', 'mnth', 'hr', 'weekday']
for each in dummy_fields:
dummies = pd.get_dummies(rides[each], prefix=each, drop_first=False)
rides = pd.concat([rides, dummies], axis=1)
fields_to_drop = ['instant', 'dteday', 'season', 'weathersit',
'weekday', 'atemp', 'mnth... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Scaling target variablesTo make training the network easier, we'll standardize each of the continuous variables. That is, we'll shift and scale the variables such that they have zero mean and a standard deviation of 1.The scaling factors are saved so we can go backwards when we use the network for predictions. | quant_features = ['casual', 'registered', 'cnt', 'temp', 'hum', 'windspeed']
# Store scalings in a dictionary so we can convert back later
scaled_features = {}
for each in quant_features:
mean, std = data[each].mean(), data[each].std()
scaled_features[each] = [mean, std]
data.loc[:, each] = (data[each] - me... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Splitting the data into training, testing, and validation setsWe'll save the data for the last approximately 21 days to use as a test set after we've trained the network. We'll use this set to make predictions and compare them with the actual number of riders. | # Save data for approximately the last 21 days
test_data = data[-21*24:]
# Now remove the test data from the data set
data = data[:-21*24]
# Separate the data into features and targets
target_fields = ['cnt', 'casual', 'registered']
features, targets = data.drop(target_fields, axis=1), data[target_fields]
test_feat... | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
We'll split the data into two sets, one for training and one for validating as the network is being trained. Since this is time series data, we'll train on historical data, then try to predict on future data (the validation set). | # Hold out the last 60 days or so of the remaining data as a validation set
train_features, train_targets = features[:-60*24], targets[:-60*24]
val_features, val_targets = features[-60*24:], targets[-60*24:] | _____no_output_____ | MIT | project-bikesharing/Predicting_bike_sharing_data.ipynb | pasbury/udacity-deep-learning-v2-pytorch |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.