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 |
|---|---|---|---|---|---|
**Incluir a coluna nova no dataframe** | df_viagem['cidade_destino'] = col[0] | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Separar conteudos diferentes que estão na mesma coluna**A coluna do dataframe possui valores nulos, estados e países misturados. Para resolver isso é preciso identificar **padrões**. No caso desse dataframe, o padrão é: - **Estados** tem só **2 caracteres**- **Paises** estão escritos com nome completo, ou seja tem ma... | df_viagem['Provisoria'] = col[1] | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Criando um dataframe para cada conteudo separado**Todos os dataframes vão ter uma coluna chamda 'Provisoria' com o conteudo separado por conteudo que foi filtrado a partir do dataframe original 'df_viagem'. Para isso filtrarei usando a função `len()`. Essa função apresenta a quantidade de conteúdo que for passado por... | #Estou colocando na coluna estado o conteudo da coluna provisória que tenha apenas dois caracteres
estado = df_viagem[df_viagem['Provisoria'].str.len()==2] | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
Agora vou criar um dataframe com o conteudo de paises, incluindo nele todo conteudo que tenha informações maior que dois caracteres | pais = df_viagem[df_viagem['Provisoria'].str.len() > 2] | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
E por fim vou criar um dataframe com o conteudo None. A função `isnull()` identifica os valores nulos no dataframe. No caso do exemplo está identificando na coluna 'Provisoria' | nulo = df_viagem[df_viagem['Provisoria'].isnull()] | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Renomeado as colunas dos dataframes** Se na coluna 'Provisoria' do dataframe 'estado' só tem o conteudo relacionado aos estados, basta renomear a coluna 'Provisoria' para 'estado'. | #No dicionario é passado na chave o nome da coluna antiga e no valor o nome que quer renomear
#O inplace serve para tornar a mudança definitiva
estado.rename(columns = {'Provisoria' : 'estado'}, inplace = True) | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
Todas os estados são relacionados ao Brasil. Então vou criar dentro do dataframe 'estado' a coluna 'pais' e incluir o conteudo 'Brasil' | estado['país'] = 'Brasil' | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
No dataframe 'pais' vou renomear a coluna 'Provisoria' para 'país' | pais.rename(columns = {'Provisoria' : 'país'}, inplace = True) | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
Como os outros paises não tem a informação do estado (no caso desse dataframe), vou criar uma coluna 'estado' e incluir o conteudo 'Sem informação' | pais['estado'] = 'Sem informação' | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
No dataframe nulo, vou renomear a coluna 'Provisoria' para 'estado' | nulo.rename(columns = {'Provisoria' : 'estado'}, inplace = True) | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
E inserir uma coluna 'país' com o conteudo 'Sem informação' | nulo['país'] = 'Sem informação' | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
Vou mudar o conteudo 'None' da coluna 'Estado' para 'Sem informação' | nulo['estado'] = 'Sem informação' | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Ordenando Colunas** A ordem das colunas novas nos novos dataframes deveria ser 'cidade_destino', 'estado' e 'pais', mas essa ordem está diferente no dataframe 'pais'. Vou reordenar para todos ficarem iguais. 1. Pegarei o nome de todas as colunas | pais.columns | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
2. Agora copio todas as colunas dentro dos colchetes duplos na ordem que eu considerar certa | pais = pais[['Identificador do processo de viagem', 'Situação',
'Código do órgão superior', 'Nome do órgão superior',
'Código órgão solicitante', 'Nome órgão solicitante', 'CPF viajante',
'Nome', 'Cargo', 'Período - Data de início', 'Período - Data de fim',
'Destinos', 'Motivo', 'Valor diári... | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Juntar os 3 dataframes em 1** | #ignore_true serve pra ignorar o indice de cada dataframe, se não vai ser impossivel junta-los
df_final = pd.concat([estado, pais, nulo], ignore_index = True) | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Removendo uma coluna**Agora não faz mais sentido ter a coluna 'Destinos' afinal ela já foi tratada. Usarei o método `drop()` para fazer isso. | #O axis indica se eu quero fazer minha alteração em uma linha ou em uma coluna. 1 é coluna, 0 é linha.
df_final.drop('Destinos', inplace = True, axis = 1) | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
**Salvando um arquivo em csv**É importante depois de tratado gerar um arquivo novo para não precisar rodar tudo e novo. | df_final.to_csv('viagens_tratado_2019.csv', encoding = 'latin-1', sep = ';') | _____no_output_____ | MIT | Tratamento de dados.ipynb | anicelysantos/jornalismo-de-dados-udemy |
Model Definition | class LeNet(torch.nn.Module):
def __init__(self):
super().__init__()
### START YOUR CODE HERE ### (You can change anything inside this block)
num_input_nodes = 32*32
num_hidden_nodes = 64
num_classes = 10
self.classifier = torch.nn.Sequential(
to... | _____no_output_____ | MIT | assignment2/task2b.ipynb | Hallvardd/TDT4195-StarterCode |
Hyperparameters & Loss function | # Hyperparameters
batch_size = 64
learning_rate = 0.0192
num_epochs = 4
# Use CrossEntropyLoss for multi-class classification
loss_function = torch.nn.CrossEntropyLoss() | _____no_output_____ | MIT | assignment2/task2b.ipynb | Hallvardd/TDT4195-StarterCode |
Train model |
image_transform = torchvision.transforms.Compose([
torchvision.transforms.Resize((32, 32)),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize([0.5], [0.25])
])
dataloader_train, dataloader_val = dataloaders.load_dataset(batch_size, image_transform)
# Model definition
model = LeNet()
# T... | _____no_output_____ | MIT | assignment2/task2b.ipynb | Hallvardd/TDT4195-StarterCode |
Train Model | utils.plot_loss(train_loss_dict, label="Train Loss")
utils.plot_loss(val_loss_dict, label="Test Loss")
# Limit the y-axis of the plot (The range should not be increased!)
plt.ylim([0, .4])
plt.legend()
plt.xlabel("Global Training Step")
plt.ylabel("Cross Entropy Loss")
os.makedirs("image_processed", exist_ok=True)
plt.... | _____no_output_____ | MIT | assignment2/task2b.ipynb | Hallvardd/TDT4195-StarterCode |
HW7 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
In order to ensure your plots are inline, make sure to run the matplotlib magic command. Q1 You are provided with a csv file (shoes.csv) on canvas that contains 2 columns. The first column is the height of the individuals being surveyed and the second column is their shoe size. We do not know anything else about th... | shoes = pd.read_csv('shoes.csv')
plt.scatter(shoes['HEIGHT (IN)'], shoes['SHOE SIZE (FT)'])
plt.xlabel('Height (in inches)')
plt.ylabel('Shoe Size (in feet)')
plt.title('Shoe Size by Height')
#computing the correlation coefficient using the long method:
def standardize(anylist):
'''convert any array of numbers to s... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- My actual shoe size is an 8. The model is off by about a size. Q2 The department of transportation releases flight delay information annually. We will use a small sample of this data to check if Chebychev's inequality holds.Use the airline_data.csv file. Plot the distribution of arrival delays. Compute the mean and... | delays = pd.read_excel('flightdelays.xlsx')
delays.shape
#cleaning data
delays = delays.dropna(subset=['ARRIVAL_DELAY'])
delays.shape
plt.style.use('fivethirtyeight')
plt.hist(delays['ARRIVAL_DELAY'], normed = True, bins = 15, ec = 'k')
plt.title('distribution of arrival delays', size = 'medium')
plt.xlabel('Delay Amou... | /anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- As per Chebychev's inequality, as least 88.88% of the data should be within 3 standard deviations of the mean... | standardized_delays = (delays['ARRIVAL_DELAY'] - np.mean(delays['ARRIVAL_DELAY'])) / np.std(delays['ARRIVAL_DELAY'])
upper_bound = np.mean(delays['ARRIVAL_DELAY']) + 3 * np.std(delays['ARRIVAL_DELAY'])
lower_bound = np.mean(delays['ARRIVAL_DELAY']) - 3 * np.std(delays['ARRIVAL_DELAY'])
within_3_SDs = np.sum(np.logical_... | 97.87234042553192
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- Yes, Chebychev's inequality is true for this dataset. | # Determining which airline to avoid...
grouped_delays = delays.groupby(['AIRLINE'], as_index=False)
grouped_delays.agg({'ARRIVAL_DELAY' : 'mean'}).sort_values('ARRIVAL_DELAY', ascending = False) | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- Based on this data alone, it would be a good idea to avoid Hawaii Airlines (HA) because it has the highest average of delay time. Q3 The NFL players data has the heights and weights of some players in the NFL. It also tells you what position they play in.1. Plot a histogram of the heights. Does this seem normally d... | nfl = pd.read_csv('nfl_players.csv', encoding='latin-1')
nfl.head()
#Plot a histogram of the heights.
plt.hist(nfl['Height'], bins = np.arange(60, 85), ec = 'blue', color = 'lightskyblue')
plt.title('distribution of heights', size = 'medium')
plt.xlabel('Player Height')
plt.ylabel('Frequency') | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The distribution looks vaguely but not quite normal. | # Mean?
np.mean(nfl['Height']) | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The mean height of NFL players is 74.013 | # Median?
np.median(nfl['Height']) | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The median height of NFL players is 74 | # Outliers?
np.max(nfl['Height']), np.min(nfl['Height']) | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The minimum and maximum values are not significant enough to be outliers. 2: Weights | #Plot a histogram of the weights.
plt.hist(nfl['Weight'], bins = np.arange(150, 370, 10), ec = 'blue', color = 'lightskyblue')
plt.title('distribution of weights', size = 'medium')
plt.xlabel('player weight')
plt.ylabel('frequency') | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The distribution of weights is not normal. | # Mean?
np.mean(nfl['Weight'])
# Median?
np.median(nfl['Weight'])
# Outliers?
np.max(nfl['Weight']), np.min(nfl['Weight'])
nfl[['Weight']].sort_values('Weight', ascending=True)[:5]
nfl[['Weight']].sort_values('Weight', ascending=False)[:5] | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- There seem to be no significantly large outliers because the data for both ends of the weight spectrum seem to be gradually increasing/decreasing. 3. Does the distribution of weights depend on the position? | nfl.columns
weight_position = nfl[['Position', 'Weight']]
weight_position.head()
# Histogramming the Distributions of Weights per Position
mpl.style.use('seaborn')
nfl.hist(column = ['Weight'], by= ['Position'], figsize = (15, 40),
layout = (12, 2), sharey = False, sharex = False,
... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- As we can see in the histograms above, the distribution of weights among players of different positions changes. Therefore, yes, the distribution of weights depends on the position. Q4 According to a fun statistics blog "The consumption of ice cream (pints per person) and the number of murders in New York are positi... | music = pd.read_csv('music.csv')
music.shape, music.columns
music = music.rename(columns = {'terms' : 'genre'})
print(music.shape)
music.head(5)
#removing songs where song.hottnesss is 0 (outliers)
music = music[music['song.hotttnesss'] != 0] | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
b. Who are the top 10 artists in terms of artist hotness? | sorted_hot_artists = music.sort_values(['artist.hotttnesss'], ascending=False)
top10 = sorted_hot_artists['artist.name'].unique()[:10]
print('These are the top 10 artists by hotness:')
for x in top10:
print(x) | These are the top 10 artists by hotness:
Kanye West
Daft Punk
Black Eyed Peas / Terry Dexter
Black Eyed Peas
Taylor Swift
Coldplay
Rihanna
Eminem
T.I.
Usher
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
Which are the top 10 songs in terms of hotness? | song_hotness = music[['song.hotttnesss', 'artist.name', 'title']]
top_10_songs = song_hotness.sort_values('song.hotttnesss', ascending = False)[:10]
top_10_songs[['title', 'song.hotttnesss', 'artist.name']] | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- These are the top 10 songs in terms of hotness. c. Create 5 different scatter plots 1) Tempo's Effect on Song Hotness. | music = music.dropna(subset = ['familiarity', 'song.hotttnesss'])
r = np.corrcoef(music['familiarity'], music['song.hotttnesss'])
r | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- the correlation coefficient r, 0.5439, tells us that there is a significant relationship between familiarity and song hotness. | m, b = np.polyfit(music['familiarity'], music['song.hotttnesss'], 1)
plt.figure(figsize=(10,5))
plt.scatter(music['familiarity'], music['song.hotttnesss'], color = 'dodgerblue')
#regression line
xvals = np.arange(0, 1.1, 0.1)
yvals = m * xvals + b
plt.plot(xvals, yvals, color = 'navy')
plt.title('Song Hotness by Fam... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The scatterplot shows that higher familiarity is significantly correlated with more popular songs; in general, the higher the familiarity, the hotter the song should be. This may be because people like to listen to songs over and over, familiar songs are catchy and easy to sing along to. 2) Duration's Effect on Son... | music = music.dropna(subset = ['duration', 'song.hotttnesss'])
#removing that one nasty outlier song that lasted over 2,050
cleaned_music = music[music['duration'] < np.max(music['duration'])]
r = np.corrcoef(cleaned_music['duration'], cleaned_music['song.hotttnesss'])
r
plt.figure(figsize=(10,5))
m, b = np.polyfit(c... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The scatter plot shows that as song duration increases past 750, there are fewer songs with high hotness. This is probably because people have short attention spans and like music in the 3 - 4 minute range; 30 minute songs are too long to hit the popular charts. 3) Key's Effect on Song Hotness. | music = music.dropna(subset = ['key', 'song.hotttnesss'])
r = np.corrcoef(music['key'], music['song.hotttnesss'])
r
#removing that one nasty outlier key:
cleaned_music = music[music['key'] < np.max(music['key'])]
r = np.corrcoef(cleaned_music['key'], cleaned_music['song.hotttnesss'])
r | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The correlation coefficient 0.001238 tells us that there is basically no linear relationship between key and song hottness. | plt.figure(figsize=(10,5))
m, b = np.polyfit(cleaned_music['key'], cleaned_music['song.hotttnesss'], 1)
plt.scatter(cleaned_music['key'], cleaned_music['song.hotttnesss'], color = 'blue')
#regression line
xvals = np.arange(0, 10, 5)
yvals = m * xvals + b
plt.title('Song Hotness by Key', size = 'medium')
plt.xlabel('k... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The scatter plot shows that there is generally an even distribution of hot songs by key. Therefore key has very little to no influence on the song's hotness. 4) Loudness' Effect on Song Hotness. | music = music.dropna(subset = ['loudness', 'song.hotttnesss'])
r = np.corrcoef(music['loudness'], music['song.hotttnesss'])
r | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- the correlation coefficient r, 0.22587, tells us that there is a very slight linear relationship between song loudness and song hotness. | plt.figure(figsize=(10,5))
m, b = np.polyfit(music['loudness'], music['song.hotttnesss'], 1)
plt.scatter(music['loudness'], music['song.hotttnesss'], color = 'dodgerblue')
#regression line
xvals = np.arange(-45, 0, 1)
yvals = m * xvals + b
plt.plot(xvals, yvals, color = 'navy')
plt.title('Song Hotness by Loudness', ... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The scatter plot shows that the number of hot songs is concentrated around louder songs; loudness has somewhat of an influence on the song's hotness. This might be because loud songs are popular among young adults for dancing. | music.columns | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
5) Artist's hotness on song's hotness | music = music.dropna(subset = ['artist.hotttnesss', 'song.hotttnesss'])
r = np.corrcoef(music['artist.hotttnesss'], music['song.hotttnesss'])
r | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The correlation coefficient r = 0.5223 shows that there is a relatively strong linear relationship between an artist's hotness and the song's hotness. | plt.figure(figsize=(10,5))
m, b = np.polyfit(music['artist.hotttnesss'], music['song.hotttnesss'], 1)
plt.scatter(music['artist.hotttnesss'], music['song.hotttnesss'], color = 'royalblue')
#regression line
xvals = np.arange(0, 1.2, .1)
yvals = m * xvals + b
plt.plot(xvals, yvals, color = 'navy')
plt.title('Song Hotn... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The scatterplot shows that there is a considerable relationship between an artist's hotness and their song's hotness. An explanation: the hotter an artist is, the larger their fanbase is. The larger the fanbase, the larger potential receptive audience for the song which means higher hotness. d) Create a linear regre... | import statsmodels.api as sm
# create a df of the independent variables
X = music[['artist.hotttnesss', 'familiarity', 'loudness']]
# dependent variable. what are we predicting?
y = music['song.hotttnesss']
#we are fitting y = ax_1 + bx_2+ c and not just ax_1 + bx_2
X = sm.add_constant(X)
# OLS - ordinary least squar... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The model is: predicted song hotness = 0.1273 + 0.3121x + 0.3652y + 0.0032z .... where x is the song artist's hotness, y is the song's familiarity, and z is the song's loudness. Q6 Use the automobilie datasetPlot the distribution of the car mileage. Does this look like a normal distribution?Plot 3 different distr... | automobiles = pd.read_csv('auto-mpg.csv')
automobiles = automobiles.dropna(subset= ['mpg', 'origin', 'weight', 'horsepower',
'model year', 'displacement', 'acceleration']) | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
Plot the distribution of the car mileage. Does this look like a normal distribution? | plt.hist(automobiles['mpg'], normed = True, bins = np.arange(5, 50), ec = 'k')
plt.xlabel('Mileage', size = 'medium')
plt.ylabel('Frequency', size = 'medium')
plt.title('Mileage Distribution for All Cars') | /anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- no, the distribution does not completely look like a normal distribution but it looks vaguely like one. Plot 3 different distributions based on the origin of the car. Which of the 3 is most normally distributed? | np.unique(automobiles['origin'])
origin_1 = automobiles[automobiles['origin'] == 1]
origin_2 = automobiles[automobiles['origin'] == 2]
origin_3 = automobiles[automobiles['origin'] == 3] | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
mileage distribution for origin 1, USA | # mileage distribution for origin 1, USA
plt.hist(standardize(origin_1['mpg']), normed = True, bins = 20, ec = 'k')
plt.xlabel('Mileage for Origin 1 (USA)', size = 'medium')
plt.ylabel('Frequency', size = 'medium')
plt.title('Mileage Distribution for Origin 1 (USA) Cars') | /anaconda3/lib/python3.6/site-packages/matplotlib/axes/_axes.py:6462: UserWarning: The 'normed' kwarg is deprecated, and has been replaced by the 'density' kwarg.
warnings.warn("The 'normed' kwarg is deprecated, and has been "
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- If you squint, this looks vaguely normally distributed. | # looking at the percent of data that lies between k standard deviations.
k = 1
upper_bound = np.mean(origin_1['mpg']) + k * np.std(origin_1['mpg'])
lower_bound = np.mean(origin_1['mpg']) - k * np.std(origin_1['mpg'])
within_3_SDs = np.sum(np.logical_and(origin_1['mpg'] < upper_bound, origin_1['mpg'] > lower_bound))
pr... | 68.67469879518072
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- We see that about 69% of the data lies between 1 standard dev. from the mean for origin 1 mileage. mileage distribution for origin 2, Germany | # mileage distribution for origin 2, Germany
plt.hist(standardize(origin_2['mpg']), normed = True, bins = 20, ec = 'k')
plt.xlabel('Mileage for Origin 2 (GER) Cars', size = 'medium')
plt.ylabel('Frequency', size = 'medium')
plt.title('Mileage Distribution for Origin 2 (German) Cars')
# looking at the percent of data th... | 70.0
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- We see that about 70% of the data lies between 1 standard dev. from the mean for origin 2 mileage. | # mileage distribution for origin 3, Japan
plt.hist(standardize(origin_3['mpg']), normed = True, bins = 20, ec = 'k')
plt.xlabel('Mileage for Origin 3 (JPN) Cars', size = 'medium')
plt.ylabel('Frequency', size = 'medium')
plt.title('Mileage Distribution for Origin 3 (Japanese) Cars')
# looking at the percent of data th... | 60.75949367088608
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- We see that about 61% of the data lies between 1 standard dev. from the mean for origin 2 mileage. - Of the 3 origins, the mileage distribution for origin 1 (USA) visually looks the most normally distributed but origin 2 (Germany) actually has more data (70%) for grouped within 1 SD of the mean than origin 1 (68%) U... | # cleaning dataframe, removing rows with '?'
vect_float = np.vectorize(float)
automobiles = automobiles[automobiles['horsepower'] != '?']
automobiles['horsepower'] = automobiles['horsepower'].apply(vect_float)
# create a df of the independent variables
X = automobiles[['weight', 'displacement', 'horsepower']]
# depend... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The model is: predicted mpg = 44.8559 - 0.0054x -0.0058y -0.0417z .... where x is the weight, y is the displacement, and z is the horsepower. Testing the model for the 3 different cars' mileages. - we will compare the predicted mileages to the Fuel Economy Est-Combined MPG from the website. | #Car 1: 2018 Chevrolet Camaro
actual_mileage = 25
x = 3339 #weight
y = 122 #displacement
z = 275 #horsepower
predicted_mpg = 44.8559 - 0.0054*x - 0.0058*y - 0.0417*z
print('The predicted mpg for the 2018 Chevrolet Camaro is: ' + str(predicted_mpg))
print('The difference between the predicted and actual milelage:')
... | The predicted mpg for the 2018 Toyota 86 is: 20.620199999999997
The difference between the predicted and actual milelage:
3.379800000000003
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
- The model is most accurate for the 2018 Toyota 86 because the difference between the actual and predicted mileages is the smallest. Q7 Using the bodyfat.csv file, create a regression model that predicts the bodyfat based on other factors in the dataset.Remember that you have to first identify correlations before yo... | bodyfat = pd.read_excel('BodyFat.xls')
bodyfat.head()
def correlation(df, x, y):
# r = avg(standardize(x) * standardize(y))
x_std = standardize(df[x])
y_std = standardize(df[y])
return np.mean(x_std * y_std)
# The variables below have significant correlations with bodyfat
print(correlation(bodyfat, 'BOD... | 0.6131561100313141
-0.9880867267228655
0.7279941849205852
0.7028851557124898
0.8137062216427914
0.6256999272610364
0.561284376117438
| MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
Making the linear regression model for bodyfat | # create a df of the independent variables
X = bodyfat[['WEIGHT', 'DENSITY', 'ADIPOSITY', 'CHEST', 'ABDOMEN', 'HIP', 'THIGH']]
# dependent variable. what are we predicting?
y = bodyfat['BODYFAT']
X = sm.add_constant(X)
# OLS - ordinary least squares.
# best possible hyperplane through the data
# best = minimize sum o... | _____no_output_____ | MIT | .ipynb_checkpoints/Regression Exploration-checkpoint.ipynb | elizabethvo/DataPy |
作業 : (Kaggle)房價預測 [作業目標]- 試著模仿範例寫法, 在房價預測中, 觀察去除離群值的影響 [作業重點]- 觀察將極端值以上下限值取代, 對於分布與迴歸分數的影響 (In[5], Out[5])- 觀察將極端值資料直接刪除, 對於分布與迴歸分數的影響 (In[6], Out[6]) | # 做完特徵工程前的所有準備 (與前範例相同)
import pandas as pd
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
# data_path = 'data/'
df_train = pd.read_csv('house_train.csv.gz')
train_Y = np.log1p(df_train['SalePrice'... | _____no_output_____ | MIT | Day_010_HW.ipynb | b15145456/6th-ML-Marathon |
作業1* 試著限制 '1樓地板面積(平方英尺)' (1stFlrSF) 欄位的上下限, 看看能否再進一步提高分數? | # 顯示 1stFlrSF 與目標值的散佈圖
import seaborn as sns
import matplotlib.pyplot as plt
sns.regplot(x = df['1stFlrSF'][:train_num], y=train_Y)
plt.show()
# 做線性迴歸, 觀察分數
train_X = MMEncoder.fit_transform(df)
estimator = LinearRegression()
cross_val_score(estimator, train_X, train_Y, cv=5).mean()
# 將 1stFlrSF 限制在你覺得適合的範圍內, 調整離群值
""... | _____no_output_____ | MIT | Day_010_HW.ipynb | b15145456/6th-ML-Marathon |
作業2* 續前題, 去除離群值有兩類方式 : 捨棄離群值(刪除離群的資料) 以及調整離群值, 請試著用同樣的上下限, 改為 '捨棄離群值' 的方法, 看看結果會變好還是變差? 並試著解釋原因。 | # 將 1stFlrSF 限制在你覺得適合的範圍內, 捨棄離群值
"""
Your Code Here
"""
keep_indexs = (df['1stFlrSF']> 500) & (df['1stFlrSF']< 2250)
df = df[keep_indexs]
train_Y = train_Y[keep_indexs]
sns.regplot(x = df['1stFlrSF'], y=train_Y)
plt.show()
# df2 = df
# del_id = df2.loc[df2['1stFlrSF']>2000].index
# del_id.append(df2.loc[df2['1stFlrSF'... | _____no_output_____ | MIT | Day_010_HW.ipynb | b15145456/6th-ML-Marathon |
del_id
| _____no_output_____ | MIT | Day_010_HW.ipynb | b15145456/6th-ML-Marathon | |
February and April 2020 precipitation anomaliesIn this notebook, we will analyze precipitation anomalies of February and April 2020, which seemed to be very contrasting in weather. We use the EOBS dataset. Import packages | ##This is so variables get printed within jupyter
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
##import packages
import os
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import cartopy
import cartopy.crs as ccrs
import matplotlib.tic... | _____no_output_____ | MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
Load EOBSI downloaded EOBS (from 1950 - 2019) and the most recent EOBS data (2020) [here](https://surfobs.climate.copernicus.eu/dataaccess/access_eobs.php). Note, you have to register as E-OBS user.The data has a daily timestep. I resample the data into monthly average mm/day. I chose not to use the total monthly prec... | EOBS = xr.open_dataset('../UK_example/EOBS/rr_ens_mean_0.25deg_reg_v20.0e.nc') ## open the data
EOBS = EOBS.resample(time='1m').mean() ## Monthly averages
# EOBS = EOBS.sel(time=EOBS['time.month'] == 2) ## Select only February
EOBS | /soge-home/users/cenv0732/.conda/envs/UNSEEN-open/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice
return np.nanmean(a, axis=axis, dtype=dtype)
| MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
Here I define the attributes, that xarray uses when plotting | EOBS['rr'].attrs = {'long_name': 'rainfall', ##Define the name
'units': 'mm/day', ## unit
'standard_name': 'thickness_of_rainfall_amount'} ## original name, not used
EOBS['rr'].mean('time').plot() ## and show the 1950-2019 average February precipitation
| _____no_output_____ | MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
The 2020 data file is separate and needs the same preprocessing: | EOBS2020 = xr.open_dataset('../UK_example/EOBS/rr_0.25deg_day_2020_grid_ensmean.nc.1') #open
EOBS2020 = EOBS2020.resample(time='1m').mean() #Monthly mean
EOBS2020['rr'].sel(time='2020-04').plot() #show map
EOBS2020 ## display dataset | /soge-home/users/cenv0732/.conda/envs/UNSEEN-open/lib/python3.8/site-packages/xarray/core/nanops.py:142: RuntimeWarning: Mean of empty slice
return np.nanmean(a, axis=axis, dtype=dtype)
| MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
Plot the 2020 eventI calculate the anomaly (deviation from the mean in mm/d) and divide this by the standard deviation to obtain the standardized anomalies. | EOBS2020_anomaly = EOBS2020['rr'].groupby('time.month') - EOBS['rr'].groupby('time.month').mean('time')
EOBS2020_anomaly
EOBS2020_sd_anomaly = EOBS2020_anomaly.groupby('time.month') / EOBS['rr'].groupby('time.month').std('time')
EOBS2020_sd_anomaly.attrs = {
'long_name': 'Monthly precipitation standardized anomal... | _____no_output_____ | MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
I select February and April (tips on how to select this are appreciated) | EOBS2020_sd_anomaly
# EOBS2020_sd_anomaly.sel(time = ['2020-02','2020-04']) ## Dont know how to select this by label?
EOBS2020_sd_anomaly[[1,3],:,:] ## Dont know how to select this by label?
| _____no_output_____ | MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
And plot using cartopy! | EOBS_plots = EOBS2020_sd_anomaly[[1, 3], :, :].plot(
transform=ccrs.PlateCarree(),
robust=True,
extend = 'both',
col='time',
cmap=plt.cm.twilight_shifted_r,
subplot_kws={'projection': ccrs.EuroPP()})
for ax in EOBS_plots.axes.flat:
ax.add_feature(cartopy.feature.BORDERS, linestyle=':')
... | _____no_output_____ | MIT | doc/Notebooks/2020_contrasting_weather.ipynb | esowc/UNSEEN-open |
Collaboration Patterns By Year (International, Domestic, Internal)Using the count capability of the API, Dimensions allows you to quickly identify international, domestic, and inernal CollaborationThis notebook shows how to quickly identify international, domestic, and internal collaboration using the [Organizations d... | !pip install dimcli plotly -U --quiet
#
# load libraries
import dimcli
from dimcli.utils import *
import json, sys, time
import pandas as pd
import plotly.express as px # plotly>=4.8.1
if not 'google.colab' in sys.modules:
# make js dependecies local / needed by html exports
from plotly.offline import init_note... | _____no_output_____ | MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
1. Lookup the University that you are interested in | dsl.query("""
search organizations for "melbourne" return organizations
""").as_dataframe()
institution = "grid.1008.9" | _____no_output_____ | MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
2. Publications output by year | allpubs = dsl.query(f"""
search publications
where research_orgs.id = "{institution}"
and type="article"
and year > 2010
return year
""").as_dataframe()
allpubs.columns = ['year', 'pubs']
px.bar(allpubs, x="year", y="pubs") | Returned Year: 11
[2mTime: 5.44s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
3. International publications | international = dsl.query(f"""
search publications
where research_orgs.id = "{institution}"
and type="article"
and count(research_org_countries) > 1
and year > 2010
return year
""").as_dataframe()
international.columns = ['year', ... | Returned Year: 11
[2mTime: 0.54s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
4. Domestic | domestic = dsl.query(f"""
search publications
where research_orgs.id = "{institution}"
and type="article"
and count(research_org_countries) = 1
and year > 2010
return year
""").as_dataframe()
domestic.columns = ['year', 'domestic_... | Returned Year: 11
[2mTime: 0.66s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
5. Internal | internal = dsl.query(f"""
search publications
where research_orgs.id = "{institution}"
and type="article"
and count(research_orgs) = 1
and year > 2010
return year
""").as_dataframe()
internal.columns = ['year', 'internal_count']
p... | Returned Year: 11
[2mTime: 0.59s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
6. Joining up All metrics together | jdf = allpubs.set_index('year'). \
join(international.set_index('year')). \
join(domestic.set_index('year')). \
join(internal.set_index('year'))
jdf
px.bar(jdf, title="University of Melbourne: publications collaboration") | _____no_output_____ | MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
7. How does this compare to Australia? | auallpubs = dsl.query("""
search publications
where research_org_countries.name= "Australia"
and type="article"
and year > 2010
return year
""").as_dataframe()
auallpubs.columns = ['year', 'all_count']
auintpubs = dsl.query("""
search... | Returned Year: 11
[2mTime: 0.76s[0m
Returned Year: 11
[2mTime: 0.74s[0m
Returned Year: 11
[2mTime: 0.70s[0m
Returned Year: 11
[2mTime: 0.74s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
8. How does this compare to a different Institution (University of Toronto)? | institution = "grid.17063.33"
allpubs = dsl.query(f"""
search publications
where research_orgs.id = "{institution}"
and type="article"
and year > 2010
return year
""").as_dataframe()
allpubs.columns = ['year', 'pubs']
international = dsl.query... | Returned Year: 11
[2mTime: 0.64s[0m
Returned Year: 11
[2mTime: 0.56s[0m
Returned Year: 11
[2mTime: 0.59s[0m
Returned Year: 11
[2mTime: 0.59s[0m
| MIT | docs/cookbooks/8-organizations/4-international-collaboration-by-year.ipynb | digital-science/dimensions-api-lab |
LANL Earthquake PredictionLink to competition on KaggleThis notebook is a reimplementation of Andrews Feature Only, with some modifications. Feature EngineeringThe large training dataset needs to be prepared to closely match the test data, which comprise independent series of 150,000 acoustic measurements. Thus, the ... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
from tqdm import tqdm_notebook
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import MinMaxScaler
from scipy.signal import hilbert
from scipy.signal import hann
from scipy.signal import convolve
from... | _____no_output_____ | MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
Load Data | %%time
train = pd.read_csv('data/raw/train.csv', dtype={'acoustic_data': np.int16, 'time_to_failure': np.float32})
print(train.shape)
train.head()
train.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 629145480 entries, 0 to 629145479
Data columns (total 2 columns):
acoustic_data int16
time_to_failure float32
dtypes: float32(1), int16(1)
memory usage: 3.5 GB
| MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
The dataset is large, occupying 3.5 GB of memory and comprising over 600 million rows. The data can be visualised by sampling a small portion of it. | train_acoustic_data_small = train['acoustic_data'].values[::50]
train_time_to_failure_small = train['time_to_failure'].values[::50]
fig, ax1 = plt.subplots(figsize=(16, 8))
plt.title("acoustic_data vs time_to_failure (2% of data sampled)")
plt.plot(train_acoustic_data_small, color='b')
ax1.set_ylabel('acoustic_data', ... | _____no_output_____ | MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
Create SegmentsSlice the training data into series of 150,000 measurements. | rows = 150000
segments = int(np.floor(train.shape[0] / rows))
X_tr = pd.DataFrame(index=range(segments), dtype=np.float64)
y_tr = pd.DataFrame(index=range(segments), dtype=np.float64, columns=['time_to_failure']) | _____no_output_____ | MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
Generate FeaturesCompute features for the training and test segments. | def add_trend_feature(arr, abs_values=False):
idx = np.array(range(len(arr)))
if abs_values:
arr = np.abs(arr)
lr = LinearRegression()
lr.fit(idx.reshape(-1, 1), arr)
return lr.coef_[0]
def classic_sta_lta(x, length_sta, length_lta):
# Short Term Average and Long Term Average
sta =... | _____no_output_____ | MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
Save Prepared Datasets | X_tr.to_csv('data/processed/010_train_features.csv', index=False)
y_tr.to_csv('data/processed/010_train_target.csv', index=False)
X_test.to_csv('data/processed/010_test_features.csv', index=True) | _____no_output_____ | MIT | EarthquakePrediction/010-feature_engineering.ipynb | AidanCooper/Kaggle |
View source on GitHub Notebook Viewer Run in binder Run in Google Colab Install Earth Engine APIInstall the [Earth Engine Python API](https://developers.google.com/earth-engine/python_install) and [geehydro](https://github.com/giswqs/geehydro). The **geehydro** Python package builds on the [folium](http... | # %%capture
# !pip install earthengine-api
# !pip install geehydro | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Import libraries | import ee
import folium
import geehydro | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Authenticate and initialize Earth Engine API. You only need to authenticate the Earth Engine API once. Uncomment the line `ee.Authenticate()` if you are running this notebook for the first time or if you are getting an authentication error. | # ee.Authenticate()
ee.Initialize() | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Create an interactive map This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `... | Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID') | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Add Earth Engine Python script | dataset = ee.Image('CSP/ERGo/1_0/Global/SRTM_landforms')
landforms = dataset.select('constant')
landformsVis = {
'min': 11.0,
'max': 42.0,
'palette': [
'141414', '383838', '808080', 'EBEB8F', 'F7D311', 'AA0000', 'D89382',
'DDC9C9', 'DCCDCE', '1C6330', '68AA63', 'B5C98E', 'E1F0E5', 'a975ba',
'6f198c'
... | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Display Earth Engine data layers | Map.setControlVisibility(layerControl=True, fullscreenControl=True, latLngPopup=True)
Map | _____no_output_____ | MIT | Datasets/Terrain/srtm_landforms.ipynb | dmendelo/earthengine-py-notebooks |
Example Input | ll = LinkedListNode(1).add_to_front(LinkedListNode(2)).add_to_front(
LinkedListNode(10)).add_to_front(LinkedListNode(5)).add_to_front(
LinkedListNode(8)).add_to_front(LinkedListNode(5)).add_to_front(
LinkedListNode(3))
ll.print_forward()
ll2 = LinkedListNode(1).add_to_front(LinkedListNode(2)).add_to_front(
... | 7 -> 5 -> 8 -> 3 -> 1 -> 2 -> 1 -> None
| MIT | ch2-linked-list/2-4.ipynb | jellycsc/cracking-the-coding-interview-practice |
Example Solution (Two pointers) | def partition(node, num):
back = node
while back.next is not None:
if back.val < num:
back = back.next
else:
if back.next.val >= num:
back = back.next
else:
tmp = back.next
back.next = tmp.next
no... | 1 -> 2 -> 1 -> 3 -> 7 -> 5 -> 8 -> None
| MIT | ch2-linked-list/2-4.ipynb | jellycsc/cracking-the-coding-interview-practice |
Basic scatterplot | from bokeh.io import output_notebook, show
from bokeh.plotting import figure
# create a new plot with default tools, using figure
p = figure(plot_width=400, plot_height=400)
# add a circle renderer with a size, color, and alpha
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=15, line_color="navy", fill_color="orange",... | _____no_output_____ | MIT | TestingBokeh/.ipynb_checkpoints/TryingBasicBokeh-checkpoint.ipynb | yjzhang/uncurl_app |
Interactive visualization using sliders | from bokeh.layouts import row, column
from bokeh.models import CustomJS, ColumnDataSource, Slider
import matplotlib.pyplot as plt
x = [x*0.005 for x in range(0, 201)]
output_notebook()
source = ColumnDataSource(data=dict(x=x, y=x))
plot = figure(plot_width=400, plot_height=400)
plot.scatter('x', 'y', source=source, ... | _____no_output_____ | MIT | TestingBokeh/.ipynb_checkpoints/TryingBasicBokeh-checkpoint.ipynb | yjzhang/uncurl_app |
Ungraded lab: Distributed Strategies with TF and Keras------------------------ Welcome, during this ungraded lab you are going to perform a distributed training strategy using TensorFlow and Keras, specifically the [`tf.distribute.MultiWorkerMirroredStrategy`](https://www.tensorflow.org/api_docs/python/tf/distribute/... | import os
import sys
import json
import time | _____no_output_____ | CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
Before importing TensorFlow, make a few changes to the environment.- Disable all GPUs. This prevents errors caused by the workers all trying to use the same GPU. **For a real application each worker would be on a different machine.**- Add the current directory to python's path so modules in this directory can be import... | # Disable GPUs
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
# Add current directory to path
if '.' not in sys.path:
sys.path.insert(0, '.') | _____no_output_____ | CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
The previous step is important since this notebook relies on writting files using the magic command `%%writefile` and then importing them as modules.Now that the environment configuration is ready, import TensorFlow. | import tensorflow as tf
# Ignore warnings
tf.get_logger().setLevel('ERROR') | _____no_output_____ | CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
Dataset and model definition Next create an `mnist.py` file with a simple model and dataset setup. This python file will be used by the worker-processes in this tutorial.The name of this file derives from the dataset you will be using which is called [mnist](https://keras.io/api/datasets/mnist/) and consists of 60,000... | %%writefile mnist.py
# import os
import tensorflow as tf
import numpy as np
def mnist_dataset(batch_size):
# Load the data
(x_train, y_train), _ = tf.keras.datasets.mnist.load_data()
# Normalize pixel values for x_train and cast to float32
x_train = x_train / np.float32(255)
# Cast y_train to int64
y_trai... | Writing mnist.py
| CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
Check that the file was succesfully created: | !ls *.py | mnist.py
| CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
Import the mnist module you just created and try training the model for a small number of epochs to observe the results of a single worker to make sure everything works correctly. | # Import your mnist model
import mnist
# Set batch size
batch_size = 64
# Load the dataset
single_worker_dataset = mnist.mnist_dataset(batch_size)
# Load compiled CNN model
single_worker_model = mnist.build_and_compile_cnn_model()
# As training progresses, the loss should drop and the accuracy should increase.
sing... | Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11493376/11490434 [==============================] - 0s 0us/step
11501568/11490434 [==============================] - 0s 0us/step
Epoch 1/3
70/70 [==============================] - 4s 47ms/step - loss: 2.2809 - accuracy: 0.1750
... | CC0-1.0 | C3_W3_Lab_1_Distributed_Training.ipynb | jimfhahn/Machine-Learning-Tutorials |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.