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 Cleaning and Feature Engineering | #We are only interested in the most recent year for which data is available, 2019
WEO=WEO.drop(['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018'], axis = 1)
#Reshape the data so each country is one observation
WEO=WEO... | _____no_output_____ | CC0-1.0 | Country_Economic_Conditions_for_Cargo_Carriers.ipynb | jamiemfraser/machine_learning |
Key Findings and Insights | #Large differences betweeen the mean and median values could be an indication of outliers that are skewing the data
WEO.agg([np.mean, np.median])
#Create a scatterplot
import matplotlib.pyplot as plt
%matplotlib inline
ax = plt.axes()
ax.scatter(WEO.Volume_exports, WEO.Volume_imports)
# Label the axes
ax.set(xlabel=... | _____no_output_____ | CC0-1.0 | Country_Economic_Conditions_for_Cargo_Carriers.ipynb | jamiemfraser/machine_learning |
Hypotheses Hypothesis 1: GDP per capita and the level of investment will be significant in determining the volume of goods and services importsHypothesis 2: There will be a strong correlation between government revenues and government expendituresHypothesis 3: GDP per capita and inflation will be significant in determ... | #Set up a linear regression model for GDP per capita and evaluate
WEO=WEO.reset_index()
X = WEO['GDP_percap_constant']
X=X.values.reshape(-1,1)
y = WEO['Volume_imports']
X2 = sm.add_constant(X)
est = sm.OLS(y, X2)
est2 = est.fit()
print(est2.summary())
#Set up a linear regression model for Investment and evaluate
WEO=... | OLS Regression Results
==============================================================================
Dep. Variable: Volume_imports R-squared: 0.325
Model: OLS Adj. R-squared: 0.305
Meth... | CC0-1.0 | Country_Economic_Conditions_for_Cargo_Carriers.ipynb | jamiemfraser/machine_learning |
Is there any connection with the crime and food inspection failures? May be ! For now, I am focusing on the burgalaries only. The burglary data is the chicago's crime data filtered for burgalaries only (in the same time window i.e. first 3 months of 2019). | burglary = pd.read_json('../data/raw/burglary.json', convert_dates=['date'])
burglary.head()
shape = burglary.shape
print(" There are %d rows and %d columns in the data" % (shape[0], shape[1]))
print(burglary.info()) | There are 29133 rows and 26 columns in the data
<class 'pandas.core.frame.DataFrame'>
Int64Index: 29133 entries, 0 to 9999
Data columns (total 26 columns):
arrest 29133 non-null bool
beat 29133 non-null int64
block 29133 non-null object
case_number 2913... | MIT | notebooks/burglary_01.ipynb | drimal/chicagofood |
Let's check if there are any null values in the data. | burglary.isna().sum()
burglary['latitude'].fillna(burglary['latitude'].mode()[0], inplace=True)
burglary['longitude'].fillna(burglary['longitude'].mode()[0], inplace=True)
ax = sns.countplot(x="ward", data=burglary)
plt.title("Burglaries by Ward")
plt.show()
plt.rcParams['figure.figsize'] = 16, 5
ax = sns.countplot(x="... | _____no_output_____ | MIT | notebooks/burglary_01.ipynb | drimal/chicagofood |
Burglaries HeatMap | import gmaps
APIKEY= os.getenv('GMAPAPIKEY')
gmaps.configure(api_key=APIKEY)
def make_heatmap(locations, weights=None):
fig = gmaps.figure()
heatmap_layer = gmaps.heatmap_layer(locations)
#heatmap_layer.max_intensity = 100
heatmap_layer.point_radius = 8
fig.add_layer(heatmap_layer)
return fig
... | _____no_output_____ | MIT | notebooks/burglary_01.ipynb | drimal/chicagofood |
Set-up notebook environment NOTE: Use a QIIME2 kernel | import numpy as np
import pandas as pd
import seaborn as sns
import scipy
from scipy import stats
import matplotlib.pyplot as plt
import re
from pandas import *
import matplotlib.pyplot as plt
%matplotlib inline
from qiime2.plugins import feature_table
from qiime2 import Artifact
from qiime2 import Metadata
import biom... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Import sample metadata | meta = q2.Metadata.load('/Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/sample_metadata/12201_metadata.txt').to_dataframe()
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Separate round 1 and round 2 and exclude round 1 Zymo, Homebrew, and MagMAX Beta | meta_r1 = meta[meta['round'] == 1]
meta_clean_r1_1 = meta_r1[meta_r1['extraction_kit'] != 'Zymo MagBead']
meta_clean_r1_2 = meta_clean_r1_1[meta_clean_r1_1['extraction_kit'] != 'Homebrew']
meta_clean_r1 = meta_clean_r1_2[meta_clean_r1_2['extraction_kit'] != 'MagMax Beta']
meta_clean_r2 = meta[meta['round'] == 2]
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Remove PowerSoil samples from each round - these samples will be used as the baseline | meta_clean_r1_noPS = meta_clean_r1[meta_clean_r1['extraction_kit'] != 'PowerSoil']
meta_clean_r2_noPS = meta_clean_r2[meta_clean_r2['extraction_kit'] != 'PowerSoil']
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Create tables including only round 1 or round 2 PowerSoil samples | meta_clean_r1_onlyPS = meta_clean_r1[meta_clean_r1['extraction_kit'] == 'PowerSoil']
meta_clean_r2_onlyPS = meta_clean_r2[meta_clean_r2['extraction_kit'] == 'PowerSoil']
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Merge PowerSoil samples from round 2 with other samples from round 1, and vice versa - this will allow us to get the correlations between the two rounds of PowerSoil | meta_clean_r1_with_r2_PS = pd.concat([meta_clean_r1_noPS, meta_clean_r2_onlyPS])
meta_clean_r2_with_r1_PS = pd.concat([meta_clean_r2_noPS, meta_clean_r1_onlyPS])
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Collapse feature-table to the desired level (e.g., genus) 16S | qiime taxa collapse \
--i-table /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/16S/10_filtered_data/dna_bothPS_16S_deblur_biom_lod_noChl_noMit_sepp_gg_noNTCs_noMock.qza \
--i-taxonomy /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/16S/06_taxonomy/d... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
ITS | qiime taxa collapse \
--i-table /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/ITS/08_filtered_data/dna_bothPS_ITS_deblur_biom_lod_noNTCs_noMock.qza \
--i-taxonomy /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/ITS/06_taxonomy/dna_all_ITS_deblur_se... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Shotgun | qiime taxa collapse \
--i-table /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/shotgun/03_filtered_data/dna_bothPS_shotgun_woltka_wol_biom_noNTCs_noMock.qza \
--i-taxonomy /Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/shotgun/wol_taxonomy.qza \
... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Import feature-tables | dna_bothPS_16S_genus_qza = q2.Artifact.load('/Users/Justin/Mycelium/UCSD/00_Knight_Lab/03_Extraction_test_12201/round_02/data/16S/10_filtered_data/dna_bothPS_16S_deblur_biom_lod_noChl_noMit_sepp_gg_noNTCs_noMock_taxa_collapse_genus.qza')
dna_bothPS_ITS_genus_qza = q2.Artifact.load('/Users/Justin/Mycelium/UCSD/00_Knight... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Convert QZA to a Pandas DataFrame | dna_bothPS_16S_genus_df = dna_bothPS_16S_genus_qza.view(pd.DataFrame)
dna_bothPS_ITS_genus_df = dna_bothPS_ITS_genus_qza.view(pd.DataFrame)
dna_bothPS_shotgun_genus_df = dna_bothPS_shotgun_genus_qza.view(pd.DataFrame)
| _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Melt dataframes | dna_bothPS_16S_genus_df_melt = dna_bothPS_16S_genus_df.unstack()
dna_bothPS_ITS_genus_df_melt = dna_bothPS_ITS_genus_df.unstack()
dna_bothPS_shotgun_genus_df_melt = dna_bothPS_shotgun_genus_df.unstack()
dna_bothPS_16S_genus = pd.DataFrame(dna_bothPS_16S_genus_df_melt)
dna_bothPS_ITS_genus = pd.DataFrame(dna_bothPS_ITS... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Wrangle data into long form for each kit Wrangle metadata | # Create empty list of extraction kit IDs
ext_kit_levels = []
# Create empty list of metadata subsets based on levels of variable of interest
ext_kit = []
# Create empty list of baseline samples for each subset
bl = []
# Populate lists with round 1 data
for ext_kit_level, ext_kit_level_df in meta_clean_r1_with_... | Gathered data for Norgen
Gathered data for PowerSoil Pro
Gathered data for PowerSoil r2
Gathered data for MagMAX Microbiome
Gathered data for NucleoMag Food
Gathered data for PowerSoil r1
Gathered data for Zymo MagBead
Merged data for Norgen
Merged data for PowerSoil Pro
Merged data for PowerSoil r2
Merged data for Mag... | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
16S | list_of_lists = []
for key, value in subsets_w_bl.items():
string = ''.join(key)
#merge metadata subsets with baseline with taxonomy
meta_16S_genera = pd.merge(value, dna_bothPS_16S_genus, left_index=True, right_on='sample')
#create new column
meta_16S_genera['taxa_subject'] = meta_16S... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
ITS | list_of_lists = []
for key, value in subsets_w_bl.items():
string = ''.join(key)
#merge metadata subsets with baseline with taxonomy
meta_ITS_genera = pd.merge(value, dna_bothPS_ITS_genus, left_index=True, right_on='sample')
#create new column
meta_ITS_genera['taxa_subject'] = meta_ITS... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Shotgun | list_of_lists = []
for key, value in subsets_w_bl.items():
string = ''.join(key)
#merge metadata subsets with baseline with taxonomy
meta_shotgun_genera = pd.merge(value, dna_bothPS_shotgun_genus, left_index=True, right_on='sample')
#create new column
meta_shotgun_genera['taxa_subject'... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Code below is not used NOTE: The first cell was originally appended to the cell above | # check pearson correlation
x = meta_16S_genera_pivot_clean.iloc[:,1]
y = meta_16S_genera_pivot_clean[key]
corr = stats.pearsonr(x, y)
int1, int2 = corr
corr_rounded = round(int1, 2)
corr_str = str(corr_rounded)
x_key = key[0]
y_key = key[1]
list1 = []
list1.append(cor... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Individual correlation plots | for key, value in subsets_w_bl.items():
string = ''.join(key)
#merge metadata subsets with baseline with taxonomy
meta_16S_genera = pd.merge(value, dna_bothPS_16S_genus, left_index=True, right_on='sample')
#create new column
meta_16S_genera['taxa_subject'] = meta_16S_genera['taxa'] + me... | _____no_output_____ | MIT | code/Taxon profile analysis.ipynb | justinshaffer/Extraction_kit_benchmarking |
Health, Wealth of Nations from 1800-2008 | import os
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
from bqplot import Figure, Tooltip, Label
from bqplot import Axis, ColorAxis
from bqplot import LogScale, LinearScale, OrdinalColorScale
from bqplot import Scatter, Lines
from bqplot import CATEGORY10
from ipywidgets import HBox, VBox... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Get Data | year_start = 1800
df = pd.read_json("data_files/nations.json")
df.head()
list_rows_to_drop = \
(df['income']
.apply(len)
.where(lambda i: i < 10)
.dropna()
.index
.tolist()
)
df.drop(list_rows_to_drop, inplace=True)
dict_dfs = {}
for COL in ['income', 'lifeExpectancy', 'population']:
df1 = \
DataFrame(d... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create Tooltip | tt = Tooltip(fields=['name', 'x', 'y'],
labels=['Country', 'IncomePerCapita', 'LifeExpectancy']) | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create Scales | # Income
income_min, income_max = get_min_max_from_df(dict_dfs['income'])
x_sc = LogScale(min=income_min,
max=income_max)
# Life Expectancy
life_exp_min, life_exp_max = get_min_max_from_df(dict_dfs['lifeExpectancy'])
y_sc = LinearScale(min=life_exp_min,
max=life_exp_max)
# Popul... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create Axes | ax_y = Axis(label='Life Expectancy',
scale=y_sc,
orientation='vertical',
side='left',
grid_lines='solid')
ax_x = Axis(label='Income per Capita',
scale=x_sc,
grid_lines='solid') | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create Marks 1. Scatter | cap_income, life_exp, pop = get_data(year_start)
scatter_ = Scatter(x=cap_income,
y=life_exp,
color=df['region'],
size=pop,
names=df['name'],
display_names=False,
scales={
'x': x_... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
2. Line | line_ = Lines(x=dict_dfs['income'].loc['Angola'].values,
y=dict_dfs['lifeExpectancy'].loc['Angola'].values,
colors=['Gray'],
scales={
'x': x_sc,
'y': y_sc
},
visible=False) | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create Label | year_label = Label(x=[0.75],
y=[0.10],
font_size=50,
font_weight='bolder',
colors=['orange'],
text=[str(year_start)],
enable_move=True) | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Construct the Figure | time_interval = 10
fig_ = \
Figure(
marks=[scatter_, line_, year_label],
axes=[ax_x, ax_y],
title='Health and Wealth of Nations',
animation_duration=time_interval
)
fig_.layout.min_width = '960px'
fig_.layout.min_height = '640px'
fig_ | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Add Interactivity- Update chart when year changes | slider_ = IntSlider(
min=year_start,
max=2008,
step=1,
description='Year: ',
value=year_start)
def on_change_year(change):
"""
"""
scatter_.x, scatter_.y, scatter_.size = get_data(slider_.value)
year_label.text = [str(slider_.value)]
slider_.observe(on_change_year, 'value')
sl... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
- Display line when hovered | def on_hover(change):
"""
"""
if change.new is not None:
display(change.new)
line_.x = dict_dfs['income'].iloc[change.new + 1]
line_.y = dict_dfs['lifeExpectancy'].iloc[change.new + 1]
line_.visible = True
else:
line_.visible = False
scatter_.observe(on_hover, 'ho... | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Add Animation! | play_button = Play(
min=1800,
max=2008,
interval=time_interval
)
jslink(
(play_button, 'value'),
(slider_, 'value')
) | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
--- Create the GUI | VBox([play_button, slider_, fig_]) | _____no_output_____ | MIT | 99-Miscel/02-bqplot-B.ipynb | dushyantkhosla/dataviz |
I want to analyze changes over time in the MOT GTFS feed. Agenda:1. [Get data](Get-the-data)3. [Tidy](Tidy-it-up) | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import partridge as ptg
from ftplib import FTP
import datetime
import re
import zipfile
import os
%matplotlib inline
plt.rcParams['figure.figsize'] = (10, 5) # set default size of plots
sns.set_style("white")
sns.set_context(... | _____no_output_____ | MIT | openbus_10_stuff.ipynb | cjer/open-bus-explore |
Get the dataThere are two options - TransitFeeds and the workshop's S3 bucket. | #!aws s3 cp s3://s3.obus.hasadna.org.il/2018-04-25.zip data/gtfs_feeds/2018-04-25.zip | _____no_output_____ | MIT | openbus_10_stuff.ipynb | cjer/open-bus-explore |
Tidy it upAgain I'm using [partridge](https://github.com/remix/partridge/tree/master/partridge) for filtering on dates, and then some tidying up and transformations. | from gtfs_utils import *
local_tariff_path = 'data/sample/180515_tariff.zip'
conn = ftp_connect()
get_ftp_file(conn, file_name = TARIFF_FILE_NAME, local_zip_path = local_tariff_path )
def to_timedelta(df):
'''
Turn time columns into timedelta dtype
'''
cols = ['arrival_time', 'departure_time']
n... | _____no_output_____ | MIT | openbus_10_stuff.ipynb | cjer/open-bus-explore |
Write in the input space, click `Shift-Enter` or click on the `Play` button to execute. | (3 + 1 + 12) ** 2 + 2 * 18 | _____no_output_____ | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Give a title to the notebook by clicking on `Untitled` on the very top of the page, better not to use spaces because it will be also used for the filename Save the notebook with the `Diskette` button, check dashboard Integer division gives integer result with truncation in Python 2, float result in Python 3: | 5/3
1/3 | _____no_output_____ | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Quotes for strings | print("Hello world")
print('Hello world') | Hello world
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Look for differences | "Hello world"
print("Hello world") | Hello world
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Multiple lines in a cell | 1 + 2
3 + 4
print(1 + 2)
print(3 + 4)
print("""This is
a multiline
Hello world""") | This is
a multiline
Hello world
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Functions and help | abs(-2) | _____no_output_____ | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Write a function name followed by `?` to open the help for that function.type in a cell and execute: `abs?` Heading 1 Heading 2 Structured plain text format, it looks a lot like writing text **emails**,you can do lists:* like* thiswrite links like , or [hyperlinking words](http://www.google.com) go to to learn more ... | weight_kg = 55 | _____no_output_____ | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Once a variable has a value, we can print it: | print(weight_kg) | 55
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
and do arithmetic with it: | print('weight in pounds:')
print(2.2 * weight_kg) | weight in pounds:
121.0
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
We can also change a variable's value by assigning it a new one: | weight_kg = 57.5
print('weight in kilograms is now:')
print(weight_kg) | weight in kilograms is now:
57.5
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
As the example above shows,we can print several things at once by separating them with commas.If we imagine the variable as a sticky note with a name written on it,assignment is like putting the sticky note on a particular value: This means that assigning a value to one variable does *not* change the values of other v... | weight_lb = 2.2 * weight_kg
print('weight in kilograms:')
print(weight_kg)
print('and in pounds:')
print(weight_lb) | weight in kilograms:
57.5
and in pounds:
126.5
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
and then change `weight_kg`: | weight_kg = 100.0
print('weight in kilograms is now:')
print(weight_kg)
print('and weight in pounds is still:')
print(weight_lb) | weight in kilograms is now:
100.0
and weight in pounds is still:
126.5
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Since `weight_lb` doesn't "remember" where its value came from,it isn't automatically updated when `weight_kg` changes.This is different from the way spreadsheets work. Challenge | x = 5
y = x
x = x**2 | _____no_output_____ | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
How much is `x`? how much is `y`? Comments | weight_kg = 100.0 # assigning weight
# now convert to pounds
print(2.2 * weight_kg) | 220.0
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Strings slicing | my_string = "Hello world"
print(my_string) | Hello world
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Python by convention starts indexing from `0` | print(my_string[0:3])
print(my_string[:3]) | Hel
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Python uses intervals open on the right: $ \left[7, 9\right[ $ | print(my_string[7:9]) | or
| BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr |
Challenge What happens if you print: | print(my_string[4:4]) | BSD-3-Clause | python_hpc/3_intro_pandas/0-intro-python.ipynb | sdsc-scicomp/2018-11-02-comet-workshop-ucr | |
Saving and Loading ModelsIn this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data. | %matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms
import helper
import fc_model
# Define a transform to normalize the data
transform =... | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Here we can see one of the images. | image, label = next(iter(trainloader))
helper.imshow(image[0,:]); | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Train a networkTo make things more concise here, I moved the model architecture and training code from the last part to a file called `fc_model`. Importing this, we can easily create a fully-connected network with `fc_model.Network`, and train the network using `fc_model.train`. I'll use this model (once it's trained)... | # Create the network, define the criterion and optimizer
model = fc_model.Network(784, 10, [512, 256, 128])
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
fc_model.train(model, trainloader, testloader, criterion, optimizer, epochs=2) | Epoch: 1/2.. Training Loss: 1.673.. Test Loss: 0.934.. Test Accuracy: 0.662
Epoch: 1/2.. Training Loss: 1.027.. Test Loss: 0.711.. Test Accuracy: 0.718
Epoch: 1/2.. Training Loss: 0.857.. Test Loss: 0.669.. Test Accuracy: 0.740
Epoch: 1/2.. Training Loss: 0.792.. Test Loss: 0.716.. Test Accuracy: 0.709
Epoc... | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Saving and loading networksAs you can imagine, it's impractical to train a network every time you need to use it. Instead, we can save trained networks then load them later to train more or use them for predictions.The parameters for PyTorch networks are stored in a model's `state_dict`. We can see the state dict cont... | print("Our model: \n\n", model, '\n')
print("The state dict keys: \n\n", model.state_dict().keys()) | Our model:
Network(
(hidden_layers): ModuleList(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): Linear(in_features=512, out_features=256, bias=True)
(2): Linear(in_features=256, out_features=128, bias=True)
)
(output): Linear(in_features=128, out_features=10, bias=True)
(dropout):... | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
The simplest thing to do is simply save the state dict with `torch.save`. For example, we can save it to a file `'checkpoint.pth'`. | torch.save(model.state_dict(), 'checkpoint.pth') | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Then we can load the state dict with `torch.load`. | state_dict = torch.load('checkpoint.pth')
print(state_dict.keys()) | odict_keys(['hidden_layers.0.weight', 'hidden_layers.0.bias', 'hidden_layers.1.weight', 'hidden_layers.1.bias', 'hidden_layers.2.weight', 'hidden_layers.2.bias', 'output.weight', 'output.bias'])
| MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
And to load the state dict in to the network, you do `model.load_state_dict(state_dict)`. | model.load_state_dict(state_dict) | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Seems pretty straightforward, but as usual it's a bit more complicated. Loading the state dict works only if the model architecture is exactly the same as the checkpoint architecture. If I create a model with a different architecture, this fails. | # Try this
model = fc_model.Network(784, 10, [400, 200, 100])
# This will throw an error because the tensor sizes are wrong!
model.load_state_dict(state_dict) | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
This means we need to rebuild the model exactly as it was when trained. Information about the model architecture needs to be saved in the checkpoint, along with the state dict. To do this, you build a dictionary with all the information you need to compeletely rebuild the model. | checkpoint = {'input_size': 784,
'output_size': 10,
'hidden_layers': [each.out_features for each in model.hidden_layers],
'state_dict': model.state_dict()}
torch.save(checkpoint, 'checkpoint.pth') | _____no_output_____ | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
Now the checkpoint has all the necessary information to rebuild the trained model. You can easily make that a function if you want. Similarly, we can write a function to load checkpoints. | def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
model = fc_model.Network(checkpoint['input_size'],
checkpoint['output_size'],
checkpoint['hidden_layers'])
model.load_state_dict(checkpoint['state_dict'])
return model
model = ... | Network(
(hidden_layers): ModuleList(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): Linear(in_features=512, out_features=256, bias=True)
(2): Linear(in_features=256, out_features=128, bias=True)
)
(output): Linear(in_features=128, out_features=10, bias=True)
(dropout): Dropout(p=0.5... | MIT | Part 6 - Saving and Loading Models.ipynb | manganganath/DL_PyTorch |
import packages | import pandas as pd | _____no_output_____ | MIT | filling missing values.ipynb | bharath1604/pandas |
1.Load data and read | california=pd.read_csv('https://raw.githubusercontent.com/bharath1604/Handling_Missing_Values/master/california_cities.csv',header=None)
california | _____no_output_____ | MIT | filling missing values.ipynb | bharath1604/pandas |
2.Drop the nan values by using (dropna()) [axis=0 means rows and axis=1 means columns] | california.dropna() | _____no_output_____ | MIT | filling missing values.ipynb | bharath1604/pandas |
Deep Learning & Art: Neural Style TransferWelcome to the second assignment of this week. In this assignment, you will learn about Neural Style Transfer. This algorithm was created by Gatys et al. (2015) (https://arxiv.org/abs/1508.06576). **In this assignment, you will:**- Implement the neural style transfer algorithm... | import os
import sys
import scipy.io
import scipy.misc
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
from PIL import Image
from nst_utils import *
import numpy as np
import tensorflow as tf
%matplotlib inline | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
1 - Problem StatementNeural Style Transfer (NST) is one of the most fun techniques in deep learning. As seen below, it merges two images, namely, a "content" image (C) and a "style" image (S), to create a "generated" image (G). The generated image G combines the "content" of the image C with the "style" of image S. In... | model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat")
print(model) | {'input': <tf.Variable 'Variable:0' shape=(1, 300, 400, 3) dtype=float32_ref>, 'conv1_1': <tf.Tensor 'Relu:0' shape=(1, 300, 400, 64) dtype=float32>, 'conv1_2': <tf.Tensor 'Relu_1:0' shape=(1, 300, 400, 64) dtype=float32>, 'avgpool1': <tf.Tensor 'AvgPool:0' shape=(1, 150, 200, 64) dtype=float32>, 'conv2_1': <tf.Tensor ... | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
The model is stored in a python dictionary where each variable name is the key and the corresponding value is a tensor containing that variable's value. To run an image through this network, you just have to feed the image to the model. In TensorFlow, you can do so using the [tf.assign](https://www.tensorflow.org/api_d... | content_image = scipy.misc.imread("images/louvre.jpg")
imshow(content_image) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
The content image (C) shows the Louvre museum's pyramid surrounded by old Paris buildings, against a sunny sky with a few clouds.** 3.1.1 - How do you ensure the generated image G matches the content of the image C?**As we saw in lecture, the earlier (shallower) layers of a ConvNet tend to detect lower-level features s... | # GRADED FUNCTION: compute_content_cost
def compute_content_cost(a_C, a_G):
"""
Computes the content cost
Arguments:
a_C -- tensor of dimension (1, n_H, n_W, n_C),
hidden layer activations representing content of the image C
a_G -- tensor of dimension (1, n_H, n_W, n_C),
hid... | J_content = 6.76559
| Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Expected Output**: **J_content** 6.76559 **What you should remember**:- The content cost takes a hidden layer activation of the neural network, and measures how different $a^{(C)}$ and $a^{(G)}$ are. - When we minimize the content cost later, this will help... | style_image = scipy.misc.imread("images/monet_800600.jpg")
imshow(style_image) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
This painting was painted in the style of *[impressionism](https://en.wikipedia.org/wiki/Impressionism)*.Lets see how you can now define a "style" const function $J_{style}(S,G)$. 3.2.1 - Style matrixThe style matrix is also called a "Gram matrix." In linear algebra, the Gram matrix G of a set of vectors $(v_{1},\dot... | # GRADED FUNCTION: gram_matrix
def gram_matrix(A):
"""
Argument:
A -- matrix of shape (n_C, n_H*n_W)
Returns:
GA -- Gram matrix of A, of shape (n_C, n_C)
"""
### START CODE HERE ### (≈1 line)
GA = tf.matmul(A, tf.transpose(A))
### END CODE HERE ###
return GA
tf.re... | GA = [[ 6.42230511 -4.42912197 -2.09668207]
[ -4.42912197 19.46583748 19.56387138]
[ -2.09668207 19.56387138 20.6864624 ]]
| Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Expected Output**: **GA** [[ 6.42230511 -4.42912197 -2.09668207] [ -4.42912197 19.46583748 19.56387138] [ -2.09668207 19.56387138 20.6864624 ]] 3.2.2 - Style cost After generating the Style matrix (Gram matrix), your goal will be to minimize the d... | # GRADED FUNCTION: compute_layer_style_cost
def compute_layer_style_cost(a_S, a_G):
"""
Arguments:
a_S -- tensor of dimension (1, n_H, n_W, n_C),
hidden layer activations representing style of the image S
a_G -- tensor of dimension (1, n_H, n_W, n_C),
hidden layer activations represe... | J_style_layer = 9.19028
| Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Expected Output**: **J_style_layer** 9.19028 3.2.3 Style WeightsSo far you have captured the style from only one layer. We'll get better results if we "merge" style costs from several different layers. After completing this exercise, feel free to come back... | STYLE_LAYERS = [
('conv1_1', 0.2),
('conv2_1', 0.2),
('conv3_1', 0.2),
('conv4_1', 0.2),
('conv5_1', 0.2)] | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
You can combine the style costs for different layers as follows:$$J_{style}(S,G) = \sum_{l} \lambda^{[l]} J^{[l]}_{style}(S,G)$$where the values for $\lambda^{[l]}$ are given in `STYLE_LAYERS`. We've implemented a compute_style_cost(...) function. It simply calls your `compute_layer_style_cost(...)` several times, and... | def compute_style_cost(model, STYLE_LAYERS):
"""
Computes the overall style cost from several chosen layers
Arguments:
model -- our tensorflow model
STYLE_LAYERS -- A python list containing:
- the names of the layers we would like
to extract ... | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Note**: In the inner-loop of the for-loop above, `a_G` is a tensor and hasn't been evaluated yet. It will be evaluated and updated at each iteration when we run the TensorFlow graph in model_nn() below.<!-- How do you choose the coefficients for each layer? The deeper layers capture higher-level concepts, and the fea... | # GRADED FUNCTION: total_cost
def total_cost(J_content, J_style, alpha = 10, beta = 40):
"""
Computes the total cost function
Arguments:
J_content -- content cost coded above
J_style -- style cost coded above
alpha -- hyperparameter weighting the importance of the content cost
beta -- ... | J = 35.34667875478276
| Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Expected Output**: **J** 35.34667875478276 **What you should remember**:- The total cost is a linear combination of the content cost $J_{content}(C,G)$ and the style cost $J_{style}(S,G)$- $\alpha$ and $\beta$ are hyperparameters that control the relative w... | # Reset the graph
tf.reset_default_graph()
# Start interactive session
sess = tf.InteractiveSession() | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Let's load, reshape, and normalize our "content" image (the Louvre museum picture): | content_image = scipy.misc.imread("images/louvre_small.jpg")
content_image = reshape_and_normalize_image(content_image) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Let's load, reshape and normalize our "style" image (Claude Monet's painting): | style_image = scipy.misc.imread("images/monet.jpg")
style_image = reshape_and_normalize_image(style_image) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Now, we initialize the "generated" image as a noisy image created from the content_image. By initializing the pixels of the generated image to be mostly noise but still slightly correlated with the content image, this will help the content of the "generated" image more rapidly match the content of the "content" image. ... | generated_image = generate_noise_image(content_image)
imshow(generated_image[0]) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Next, as explained in part (2), let's load the VGG16 model. | model = load_vgg_model("pretrained-model/imagenet-vgg-verydeep-19.mat") | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
To get the program to compute the content cost, we will now assign `a_C` and `a_G` to be the appropriate hidden layer activations. We will use layer `conv4_2` to compute the content cost. The code below does the following:1. Assign the content image to be the input to the VGG model.2. Set a_C to be the tensor giving th... | # Assign the content image to be the input of the VGG model.
sess.run(model['input'].assign(content_image))
# Select the output tensor of layer conv4_2
out = model['conv4_2']
# Set a_C to be the hidden layer activation from the layer we have selected
a_C = sess.run(out)
# Set a_G to be the hidden layer activation ... | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Note**: At this point, a_G is a tensor and hasn't been evaluated. It will be evaluated and updated at each iteration when we run the Tensorflow graph in model_nn() below. | # Assign the input of the model to be the "style" image
sess.run(model['input'].assign(style_image))
# Compute the style cost
J_style = compute_style_cost(model, STYLE_LAYERS) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Exercise**: Now that you have J_content and J_style, compute the total cost J by calling `total_cost()`. Use `alpha = 10` and `beta = 40`. | ### START CODE HERE ### (1 line)
J = total_cost(J_content, J_style, alpha = 10, beta = 40)
### END CODE HERE ### | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
You'd previously learned how to set up the Adam optimizer in TensorFlow. Lets do that here, using a learning rate of 2.0. [See reference](https://www.tensorflow.org/api_docs/python/tf/train/AdamOptimizer) | # define optimizer (1 line)
optimizer = tf.train.AdamOptimizer(2.0)
# define train_step (1 line)
train_step = optimizer.minimize(J) | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
**Exercise**: Implement the model_nn() function which initializes the variables of the tensorflow graph, assigns the input image (initial generated image) as the input of the VGG16 model and runs the train_step for a large number of steps. | def model_nn(sess, input_image, num_iterations = 200):
# Initialize global variables (you need to run
# the session on the initializer)
### START CODE HERE ### (1 line)
sess.run(tf.global_variables_initializer())
### END CODE HERE ###
# Run the noisy input image (initial generated ima... | _____no_output_____ | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Run the following cell to generate an artistic image. It should take about 3min on CPU for every 20 iterations but you start observing attractive results after ≈140 iterations. Neural Style Transfer is generally trained using GPUs. | model_nn(sess, generated_image) | Iteration 0 :
total cost = 5.05035e+09
content cost = 7877.67
style cost = 1.26257e+08
Iteration 20 :
total cost = 9.43276e+08
content cost = 15186.9
style cost = 2.35781e+07
Iteration 40 :
total cost = 4.84898e+08
content cost = 16785.0
style cost = 1.21183e+07
Iteration 60 :
total cost = 3.12574e+08
content cost = 17... | Apache-2.0 | lesson4-week4/Art Generation with Neural Style Transfer - v2/Art+Generation+with+Neural+Style+Transfer+-+v2.ipynb | tryrus/Coursera-DeepLearning-AndrewNG-exercise |
Predicting Student Admissions with Neural NetworksIn this notebook, we predict student admissions to graduate school at UCLA based on three pieces of data:- GRE Scores (Test)- GPA Scores (Grades)- Class rank (1-4)The dataset originally came from here: http://www.ats.ucla.edu/ Loading the dataTo load the data and forma... | # Importing pandas and numpy
import pandas as pd
import numpy as np
# Reading the csv file into a pandas DataFrame
data = pd.read_csv('student_data.csv')
# Printing out the first 10 rows of our data
data[:10] | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Plotting the dataFirst let's make a plot of our data to see how it looks. In order to have a 2D plot, let's ingore the rank. | # Importing matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
# Function to help us plot
def plot_points(data):
X = np.array(data[["gre","gpa"]])
y = np.array(data["admit"])
admitted = X[np.argwhere(y==1)]
rejected = X[np.argwhere(y==0)]
plt.scatter([s[0][0] for s in rejected], [s[0][1]... | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Roughly, it looks like the students with high scores in the grades and test passed, while the ones with low scores didn't, but the data is not as nicely separable as we hoped it would. Maybe it would help to take the rank into account? Let's make 4 plots, each one for each rank. | # Separating the ranks
data_rank1 = data[data["rank"]==1]
data_rank2 = data[data["rank"]==2]
data_rank3 = data[data["rank"]==3]
data_rank4 = data[data["rank"]==4]
# Plotting the graphs
plot_points(data_rank1)
plt.title("Rank 1")
plt.show()
plot_points(data_rank2)
plt.title("Rank 2")
plt.show()
plot_points(data_rank3)
... | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
This looks more promising, as it seems that the lower the rank, the higher the acceptance rate. Let's use the rank as one of our inputs. In order to do this, we should one-hot encode it. TODO: One-hot encoding the rankUse the `get_dummies` function in pandas in order to one-hot encode the data.Hint: To drop a column, i... | # TODO: Make dummy variables for rank
one_hot_data = pd.concat([data, pd.get_dummies(data['rank'], prefix = 'rank_')], axis = 1)
# TODO: Drop the previous rank column
one_hot_data = one_hot_data.drop(['rank'], axis = 1)
# Print the first 10 rows of our data
one_hot_data[:10] | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
TODO: Scaling the dataThe next step is to scale the data. We notice that the range for grades is 1.0-4.0, whereas the range for test scores is roughly 200-800, which is much larger. This means our data is skewed, and that makes it hard for a neural network to handle. Let's fit our two features into a range of 0-1, by ... | # Making a copy of our data
processed_data = one_hot_data[:]
# TODO: Scale the columns
processed_data['gpa'] = processed_data['gpa'] / 4.0
processed_data['gre'] = processed_data['gre'] / 800
# Printing the first 10 rows of our procesed data
processed_data[:10] | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Splitting the data into Training and Testing In order to test our algorithm, we'll split the data into a Training and a Testing set. The size of the testing set will be 10% of the total data. | sample = np.random.choice(processed_data.index, size=int(len(processed_data)*0.9), replace=False)
train_data, test_data = processed_data.iloc[sample], processed_data.drop(sample)
print("Number of training samples is", len(train_data))
print("Number of testing samples is", len(test_data))
print(train_data[:10])
print(t... | Number of training samples is 360
Number of testing samples is 40
admit gre gpa rank__1 rank__2 rank__3 rank__4
195 0 0.700 0.8975 0 1 0 0
343 0 0.725 0.7650 0 1 0 0
125 0 0.675 0.8450 0 0 0 1
314 ... | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Splitting the data into features and targets (labels)Now, as a final step before the training, we'll split the data into features (X) and targets (y). | features = train_data.drop('admit', axis = 1)
targets = train_data['admit']
features_test = test_data.drop('admit', axis=1)
targets_test = test_data['admit']
print(features[:10])
print(targets[:10])
| gre gpa rank__1 rank__2 rank__3 rank__4
195 0.700 0.8975 0 1 0 0
343 0.725 0.7650 0 1 0 0
125 0.675 0.8450 0 0 0 1
314 0.675 0.8650 0 0 0 1
147 0.700 0.6775 0 0 1... | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Training the 2-layer Neural NetworkThe following function trains the 2-layer neural network. First, we'll write some helper functions. | # Activation (sigmoid) function
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_prime(x):
return sigmoid(x) * (1-sigmoid(x))
def error_formula(y, output):
return - y*np.log(output) - (1 - y) * np.log(1-output) | _____no_output_____ | MIT | Introduction to Neural Networks/StudentAdmissions.ipynb | kushkul/Facebook-Pytorch-Scholarship-Challenge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.