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 |
|---|---|---|---|---|---|
Adding a TooltipA `tooltip` can be added to a folium.GeoJson map layer to display data values when the mouse hovers over a feature. | # Double check what columns we have
ca_counties_gdf.columns
?folium.GeoJsonTooltip
# Define the basemap
map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map
tiles='CartoDB Positron',
width=1000, # the width & height ... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
As always, you can get more help by reading the documentation. | # Uncomment to view help
#folium.GeoJsonTooltip? | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
ExerciseEdit the code in the cell below to `add` the median age(`MED_AGE`) to the tooltip. | # Define the basemap
map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map
tiles='CartoDB Positron',
width=1000, # the width & height of the output map
height=600, # in pixels
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
*Click here for answers*<!--- Define the basemapmap1 = folium.Map(location=[37.8721, -122.2578], lat, lon around which to center the map tiles='CartoDB Positron', width=1000, the width & height of the output map height=600, ... | # Uncomment to view help docs
## folium.Choropleth? | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
With `folium.Choropleth`, we will use some of the same style parameters that we used with `folium.GeoJson`.We will also use some new parameters, as shown below.First, let's take a look at the data we will map to refresh our knowledge. | print(ca_counties_gdf.columns)
ca_counties_gdf.head(2) | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Now let's create a choropleth map of total population, which is in the `c_race` column. | ca_counties_gdf.head()
# Define the basemap
map2 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map
tiles='CartoDB Positron',
width=1000, # the width & height of the output map
height=600, ... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Choropleth Mapping with Folium - discussionLet's discuss the following lines from the code above in more detail. Add the Choropleth layerfolium.Choropleth(geo_data=ca_counties_gdf.set_index('NAME'), data=ca_counties_gdf, columns=['NAME','POP2012'], key_on="feature.id", fill_col... | # Write your thoughts here | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
ExerciseCopy and paste the code from above into the cell below to create a choropleth map of population density (`POP12_SQMI`).Feel free to experiment with any of the `folium.Choropleth` style parameters, especially the `fill_color` which needs to be one of the `color brewer palettes` listed below:fill_color: string, ... | # Your code here
# Define the basemap
map2 = folium.Map(location=[37.7749, -122.4194], # lat, lon around which to center the map
tiles='Stamen Toner',
width=1000, # the width & height of the output map
height=600, #... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
*Click here for answers*<!--- SOLUTION Get our map center ctrX = (tracts_gdf.total_bounds[0] + tracts_gdf.total_bounds[2])/2 ctrY = (tracts_gdf.total_bounds[1] + tracts_gdf.total_bounds[3])/2 Create our base map map2 = folium.Map(location=[ctrY, ctrX], tiles='CartoDB Positron'... | # Define the basemap
map3 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map
tiles='CartoDB Positron',
width=1000, # the width & height of the output map
height=600, # in pixels
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Question Do you notice anything different about the `style_function` for layer2 above? ExerciseRedo the above choropleth map code to map population density. Add both population and population density to the tooltip. Don't forget to update the legend name. | # Your code here | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
12.5 OverlaysWe can overlay other geospatial data on our folium maps.Let's say we want to focus the previous choropleth map with tooltips (`map3`) on the City of Berkeley. We can fetch the border of the city from our census Places dataset. These data can be downloaded from the Census website. We use the cartographic b... | places = gpd.read_file("zip://notebook_data/census/Places/cb_2018_06_place_500k.zip")
places.head(2)
berkeley = places[places.NAME=='Berkeley'].copy()
berkeley.head(2) | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Plot the Berkeley geodataframe to make sure it looks ok. | berkeley.plot()
# Create a new map centered on Berkeley
berkeley_map = folium.Map(location=[berkeley.centroid.y.mean(),
berkeley.centroid.x.mean()],
tiles='CartoDB Positron',
width=800,height=600,
zoom_start=13)
# Add the cens... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
QuestionsAny questions about the above map?Does the code for the Berkeley map above differ from our previous choropleth map code?Does the order of layer2 & layer3 matter (can they be switched?) ExerciseRedo the above map with population density. Create and display the Oakland city boundary on the map instead o... | # Your code here | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
*Click here for solution*<!--- SOLUTION oakland = places[places.NAME=='Oakland'].copy() oakland.plot() SOLUTION oakland_map = folium.Map(location=[oakland.centroid.y.mean(), oakland.centroid.x.mean()], tiles='CartoDB Positron', width=800,height=600, ... | # Load light rail stop data
railstops = gpd.read_file("zip://notebook_data/transportation/Passenger_Rail_Stations_2019.zip")
railstops.tail()
# Subset to keep just bart stations
bart_stations = railstops[railstops['agencyname']=='BART'].sort_values(by="station_na")
bart_stations.head()
# Repeat for the rail lines
rai... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Now that we have fetched and checked the Bart data, let's do a quick folium map with it.We will use `folium.GeoJson` to add these data to the map, just as we used it previously for the census tract polygons. | # Bart Map
map4 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
width=800,height=600,
zoom_start=10)
folium.GeoJson(bart_lines).add_to(map4)
folium.GeoJson(bart_stations).add_to(map4)
map4 # ... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
We can also add tooltips, just as we did previously. | # Bart Map
map4 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
#width=800,height=600,
zoom_start=10)
# Add Bart lines
folium.GeoJson(bart_lines,
tooltip=folium.GeoJsonTooltip(
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
That's pretty cool, but don't you just want to click on those marker points to get a `popup` rather than hovering over for a `tooltip`? Mapping PointsSo far we have used `folium.GeoJson` to map our BART points. By default this uses the push-pin marker symbology made popular by Google Maps. Under the hood, folium.GeoJs... | # Uncomment to view help docs
folium.Marker? | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Let's explicitly add the Bart Stations as points so we can change the `tooltips` to `popups`. | # Bart Map
map4 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
#width=800,height=800,
zoom_start=10)
# Add Bart lines
folium.GeoJson(bart_lines,
tooltip=folium.GeoJsonTooltip(
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
That `folium.Marker` code is a bit more complex than `folium.GeoJson` and may not be worth it unless you really want that popup behavior.But let's see what else we can do with a `folium.Marker` by viewing the next map. | # Bart Map
map4 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
#width=800,height=600,
zoom_start=10)
# Add BART lines
folium.GeoJson(bart_lines,
tooltip=folium.GeoJsonTooltip(
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
ExerciseCopy and paste the code for the previous cell into the next cell and 1. change the bart icon to "https://ya-webdesign.com/transparent450_/train-emoji-png-14.png"2. change the popup back to a tooltip. | # Your code here | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
*Click here for solution*<!--- Bart Mapmap4 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()], tiles='CartoDB Positron', width=800,height=600, zoom_start=10) Add BART linesfolium.GeoJson(bart_lines, tooltip=folium.G... | # Define the basemap
map5 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()], # lat, lon around which to center the map
tiles='CartoDB Positron',
#width=1000, # the width & height of the output map
#height=... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
folium.Circle You can also set the size of your circles to a fixed radius, in meters, using `folium.Circle`. This is great for exploratory data analysis. For example, you can see what the census tract values are within 500 meters of a BART station. | # Uncomment to view
#?folium.Circle
# Define the basemap
map5 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()], # lat, lon around which to center the map
tiles='CartoDB Positron',
#width=1000, # the width & height of the ... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
QuestionWhat do you notice about the size of the circles as you zoom in/out when you compare folium.Circles and folium.CircleMarkers? Proportional Symbol MapsOne of the advantages of the `folium.CircleMarker` is that we can set the size of the map to vary based on a data value.To give this a try, let's add a f... | # add a column to the bart stations gdf
bart_stations['millions_served'] = np.random.randint(1,10, size=len(bart_stations))
bart_stations.head()
# Define the basemap
map5 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
So if you hover over our BART stations, you see that we've formatted it nicely! Using some HTML and Python string formatting we can make our `tooltip` easier to read. If you want to learn more about customizing these, you can [go check this out to learn HTML basics](https://www.w3schools.com/html/html_basic.asp). You ... | # Create a new map centered on the census tract data
map6 = folium.Map(location=[bart_stations.centroid.y.mean(), bart_stations.centroid.x.mean()],
tiles='CartoDB Positron',
#width=800,height=600,
zoom_start=10)
# Add the counties polygons as a choropleth map
laye... | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Questions1. Take a look at the help docs `folium.LayerControl?`. What parameter would move the location of the LayerControl? What parameter would allow it to be closed by default?2. Take a look at the way we added `layer2` above (this has the census tract tooltips). How has the code we use to add the layer to t... | # Uncomment to view
#folium.LayerControl? | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Saving to an html fileBy saving our map to a html we can use it later as something to add to a website or email to a colleague.You can save any of the maps you have in the notebook using this syntax:> map_name.save("file_name.html")Let's try that. | map6.save('outdata/bartmap.html') | _____no_output_____ | MIT | 12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb | reeshav-netizen/Geospatial-Fundamentals-in-Python |
Rasters for a single spikeglx session- Load an exctractor for visualization of the data- Load the sorts as in notebook sglx_pipe-dev-sort-rasters--z_w12m7_20-20201104- load the mot_dict- plot rasters- export to npy for brad SGL spikeextractor needs spikeextractors==0.9.3, spikeinterface==0.12.0. Will break with other ... | %matplotlib inline
import os
import glob
import logging
import numpy as np
import pandas as pd
from scipy.io import wavfile
from scipy import signal
import pickle
from matplotlib import pyplot as plt
from importlib import reload
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Forma... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
get the recordings just in case | probe_id = int(sess_par['probe'].split('_')[-1])
i_run = 0
run_meta_files = {k: v[i_run] for k, v in sgl_files.items()}
run_recordings = {k: sglex.SpikeGLXRecordingExtractor(sglu.get_data_meta_path(v)[0]) for k, v in run_meta_files.items()}
| _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
load the sort and the motif dictionary | from ceciestunepipe.util.spike import kilosort as ks
from ceciestunepipe.util.sound import spectral as sp
from ceciestunepipe.util import plotutil as pu
plt.rcParams['lines.linewidth'] = 0.1
axes_pars = {'axes.labelpad': 5,
'axes.titlepad': 5,
'axes.titlesize': 'small',
'axes.gri... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
load sort | spike_pickle_path = os.path.join(exp_struct['folders']['processed'], 'spk_df.pkl')
clu_pickle_path = os.path.join(exp_struct['folders']['processed'], 'clu_df.pkl')
spk_df = pd.read_pickle(spike_pickle_path)
clu_df = pd.read_pickle(clu_pickle_path) | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
load motif dictionary | mot_dict_path = os.path.join(exp_struct['folders']['processed'], 'mot_dict.pkl')
logger.info('Loading mot_dict from {}'.format(mot_dict_path))
with open(mot_dict_path, 'rb') as handle:
mot_dict = pickle.load(handle)
mot_dict | 2021-08-27 14:23:39,729 root INFO Loading mot_dict from /mnt/cube/earneodo/bci_zf/neuropix/birds/z_w12m7_20/Ephys/processed/20201104/2500r250a_3500_dir_g0/mot_dict.pkl
| MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
make a raster | ## the start times synched to the spike time base (ap_0, comes from sglx_pipe-dev-sort-rasters notebook)
mot_samples = mot_dict['start_sample_ap_0']
mot_s_f = mot_dict['s_f']
ap_s_f = mot_dict['s_f_ap_0']
mot_samples
## get the actural raster for some clusters
def get_window_spikes(spk_df, clu_list, start_sample, end_s... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
collect all good, ra units | t_pre = - 0.5
t_post = 1.5
t_pre_samp = int(t_pre * ap_s_f)
t_post_samp = int(t_post * ap_s_f)
clu_list = np.unique(clu_df.loc[(clu_df['KSLabel']=='good') & (clu_df['nucleus'].isin(['ra'])),
'cluster_id'])
rast_arr = get_rasters(spk_df, clu_list, mot_dict['start_sample_ap_0'] + t_pre_... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
export to npy arrays | def export_spikes_array(spk_df, clu_list, start_samples, span_samples, file_path, bin_size=None):
# get the raster for the clu_list
# if necessary, bin it
# save it as numpy
rast_arr = get_rasters(spk_df, clu_list, start_samples, span_samples)
if bin_size:
logger.info('Getting binned sp... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
plot one spk_arr together with a motif | spk_arr = spk_arr_list[1]
plt.imshow(spk_arr[32, :, :].T, aspect='auto', cmap='inferno')
np.transpose(spk_arr, axes=[0, 2, 1]).shape
plt.plot(spk_arr[0].sum(axis=1))
np.transpose(rast_arr, axes=[0, 2, 1]).shape
spk_arr.shape
mot_len = mot_dict['template'].size
mot_len_s = mot_len / mot_s_f
t_pre = - 0.5
t_post = 0.5 + ... | _____no_output_____ | MIT | sglx_pipe_rasters-z_w12m7_20-20201104.ipynb | zekearneodo/ceciestunepipe |
Laboratorio 9 | import pandas as pd
import altair as alt
import matplotlib.pyplot as plt
from vega_datasets import data
alt.themes.enable('opaque')
%matplotlib inline | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
En este laboratorio utilizaremos un conjunto de datos _famoso_, el GapMinder. Esta es una versión reducida que solo considera países, ingresos, salud y población. ¿Hay alguna forma natural de agrupar a estos países? | gapminder = data.gapminder_health_income()
gapminder.head() | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
Ejercicio 1(1 pto.)Realiza un Análisis exploratorio, como mínimo un `describe` del dataframe y una visualización adecuada, por ejemplo un _scatter matrix_ con los valores numéricos. | gapminder.describe()
#scatter matrix con valores númerico
alt.Chart(gapminder).mark_circle().encode(
alt.X(alt.repeat("column"), type='quantitative'),
alt.Y(alt.repeat("row"), type='quantitative'),
).properties(
width=150,
height=150
).repeat(
row=['income', 'health', 'population'],
column=['pop... | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
__Pregunta:__ ¿Hay alguna variable que te entregue indicios a simple vista donde se puedan separar países en grupos?__Respuesta:__ En la variable población se pueden ver 3 grupos, en la variable health se observan 2 grupos y en la variable income se pueden ver 3 grupos distintos. Luego, en los otros gráficos:En el gráf... | from sklearn.preprocessing import StandardScaler
X_raw = pd.DataFrame({"income": gapminder["income"],"health": gapminder["health"],"population":gapminder["population"]}).to_numpy()
X = StandardScaler().fit_transform(X_raw) | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
Ejercicio 3(1 pto.)Definir un _estimator_ `KMeans` con `k=3` y `random_state=42`, luego ajustar con `X` y finalmente, agregar los _labels_ obtenidos a una nueva columna del dataframe `gapminder` llamada `cluster`. Finalmente, realizar el mismo gráfico del principio pero coloreado por los clusters obtenidos. | from sklearn.cluster import KMeans
k = 3
kmeans = KMeans(n_clusters=k,random_state=42)
kmeans.fit(X)
clusters = kmeans.labels_
gapminder["cluster"] = clusters
alt.Chart(gapminder).mark_circle().encode(
alt.X(alt.repeat("column"), type='quantitative'),
alt.Y(alt.repeat("row"), type='quantitative'),
color='cl... | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
Ejercicio 4(1 pto.)__Regla del codo____¿Cómo escoger la mejor cantidad de _clusters_?__En este ejercicio hemos utilizado que el número de clusters es igual a 3. El ajuste del modelo siempre será mejor al aumentar el número de clusters, pero ello no significa que el número de clusters sea el apropiado. De hecho, si ten... | elbow = pd.Series(name="inertia", dtype="float64").rename_axis(index="k")
for k in range(1, 10):
kmeans = KMeans(n_clusters=k,random_state=42).fit(X)
elbow.loc[k] = kmeans.inertia_ # Inertia: Sum of distances of samples to their closest cluster center
elbow = elbow.reset_index()
alt.Chart(elbow).mark_line(point... | _____no_output_____ | MIT | labs/lab09.ipynb | Amandaa-S/mat281_portfolio |
Residual NetworksWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](http... | import numpy as np
from keras import layers
from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.utils import layer_utils
... | Using TensorFlow backend.
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
1 - The problem of very deep neural networksLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.* The main benefit of a very deep network is that it can re... | # GRADED FUNCTION: identity_block
def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 3
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main pat... | out = [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003]
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
**Expected Output**: **out** [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003] 2.2 - The convolutional blockThe ResNet "convolutional block" is the second block type. You can use this type of block when the input and output dimensions... | # GRADED FUNCTION: convolutional_block
def convolutional_block(X, f, filters, stage, block, s=2):
"""
Implementation of the convolutional block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's win... | out = [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603]
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
**Expected Output**: **out** [ 0.09018463 1.23489773 0.46822017 0.0367176 0. 0.65516603] 3 - Building your first ResNet model (50 layers)You now have the necessary blocks to build a very deep ResNet. The following figure describes in detail the... | # GRADED FUNCTION: ResNet50
def ResNet50(input_shape=(64, 64, 3), classes=6):
"""
Implementation of the popular ResNet50 the following architecture:
CONV2D -> BATCHNORM -> RELU -> MAXPOOL -> CONVBLOCK -> IDBLOCK*2 -> CONVBLOCK -> IDBLOCK*3
-> CONVBLOCK -> IDBLOCK*5 -> CONVBLOCK -> IDBLOCK*2 -> AVGPOOL ... | _____no_output_____ | MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
Run the following code to build the model's graph. If your implementation is not correct you will know it by checking your accuracy when running `model.fit(...)` below. | model = ResNet50(input_shape = (64, 64, 3), classes = 6) | _____no_output_____ | MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
As seen in the Keras Tutorial Notebook, prior training a model, you need to configure the learning process by compiling the model. | model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) | _____no_output_____ | MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
The model is now ready to be trained. The only thing you need is a dataset. Let's load the SIGNS Dataset. **Figure 6** : **SIGNS dataset** | X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()
# Normalize image vectors
X_train = X_train_orig/255.
X_test = X_test_orig/255.
# Convert training and test labels to one hot matrices
Y_train = convert_to_one_hot(Y_train_orig, 6).T
Y_test = convert_to_one_hot(Y_test_orig, 6).T
print ("n... | number of training examples = 1080
number of test examples = 120
X_train shape: (1080, 64, 64, 3)
Y_train shape: (1080, 6)
X_test shape: (120, 64, 64, 3)
Y_test shape: (120, 6)
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
Run the following cell to train your model on 2 epochs with a batch size of 32. On a CPU it should take you around 5min per epoch. | model.fit(X_train, Y_train, epochs = 2, batch_size = 32) | Epoch 1/2
1080/1080 [==============================] - 228s - loss: 2.8833 - acc: 0.2546
Epoch 2/2
1080/1080 [==============================] - 226s - loss: 1.9659 - acc: 0.3852
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
**Expected Output**: ** Epoch 1/2** loss: between 1 and 5, acc: between 0.2 and 0.5, although your results can be different from ours. ** Epoch 2/2** loss: between 1 and 5, acc: between 0.2 and 0.5, you should ... | preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1])) | 120/120 [==============================] - 8s
Loss = 2.19054207802
Test Accuracy = 0.166666666667
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
**Expected Output**: **Test Accuracy** between 0.16 and 0.25 For the purpose of this assignment, we've asked you to train the model for just two epochs. You can see that it achieves poor performances. Please go ahead and submit your assignment; to check corre... | model = load_model('ResNet50.h5')
preds = model.evaluate(X_test, Y_test)
print ("Loss = " + str(preds[0]))
print ("Test Accuracy = " + str(preds[1])) | 120/120 [==============================] - 8s
Loss = 0.530178320408
Test Accuracy = 0.866666662693
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
ResNet50 is a powerful model for image classification when it is trained for an adequate number of iterations. We hope you can use what you've learnt and apply it to your own classification problem to perform state-of-the-art accuracy.Congratulations on finishing this assignment! You've now implemented a state-of-the-a... | img_path = 'images/my_image.jpg'
img = image.load_img(img_path, target_size=(64, 64))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = x/255.0
print('Input image shape:', x.shape)
my_image = scipy.misc.imread(img_path)
imshow(my_image)
print("class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] = "... | Input image shape: (1, 64, 64, 3)
class prediction vector [p(0), p(1), p(2), p(3), p(4), p(5)] =
[[ 3.41876671e-06 2.77412561e-04 9.99522924e-01 1.98842812e-07
1.95619068e-04 4.11686671e-07]]
| MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
You can also print a summary of your model by running the following code. | model.summary() | ____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_1 (InputLay... | MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
Finally, run the code below to visualize your ResNet50. You can also download a .png picture of your model by going to "File -> Open...-> model.png". | plot_model(model, to_file='model.png')
SVG(model_to_dot(model).create(prog='dot', format='svg')) | _____no_output_____ | MIT | Course 4 - Convolutional Neural Networks/NoteBooks/Residual_Networks_v2a.ipynb | HarshitRuwali/Coursera-Deep-Learning-Specialization |
Inferring parameters of SDEs using a Euler-Maruyama scheme_This notebook is derived from a presentation prepared for the Theoretical Neuroscience Group, Institute of Systems Neuroscience at Aix-Marseile University._ | %pylab inline
import arviz as az
import pymc3 as pm
import scipy
import theano.tensor as tt
from pymc3.distributions.timeseries import EulerMaruyama
%config InlineBackend.figure_format = 'retina'
az.style.use('arviz-darkgrid') | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Toy model 1Here's a scalar linear SDE in symbolic form$ dX_t = \lambda X_t + \sigma^2 dW_t $discretized with the Euler-Maruyama scheme | # parameters
λ = -0.78
σ2 = 5e-3
N = 200
dt = 1e-1
# time series
x = 0.1
x_t = []
# simulate
for i in range(N):
x += dt * λ * x + sqrt(dt) * σ2 * randn()
x_t.append(x)
x_t = array(x_t)
# z_t noisy observation
z_t = x_t + randn(x_t.size) * 5e-3
figure(figsize=(10, 3))
subplot(121)
plot(x_t[:30], 'k', lab... | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
What is the inference we want to make? Since we've made a noisy observation of the generated time series, we need to estimate both $x(t)$ and $\lambda$. First, we rewrite our SDE as a function returning a tuple of the drift and diffusion coefficients | def lin_sde(x, lam):
return lam * x, σ2 | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Next, we describe the probability model as a set of three stochastic variables, `lam`, `xh`, and `zh`: | with pm.Model() as model:
# uniform prior, but we know it must be negative
lam = pm.Flat('lam')
# "hidden states" following a linear SDE distribution
# parametrized by time step (det. variable) and lam (random variable)
xh = EulerMaruyama('xh', dt, lin_sde, (lam, ), shape=N, testval=x_t)
... | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Once the model is constructed, we perform inference, i.e. sample from the posterior distribution, in the following steps: | with model:
trace = pm.sample(2000, tune=1000) | Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [xh, lam]
| Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Next, we plot some basic statistics on the samples from the posterior, | figure(figsize=(10, 3))
subplot(121)
plot(percentile(trace[xh], [2.5, 97.5], axis=0).T, 'k', label=r'$\hat{x}_{95\%}(t)$')
plot(x_t, 'r', label='$x(t)$')
legend()
subplot(122)
hist(trace[lam], 30, label=r'$\hat{\lambda}$', alpha=0.5)
axvline(λ, color='r', label=r'$\lambda$', alpha=0.5)
legend(); | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
A model can fit the data precisely and still be wrong; we need to use _posterior predictive checks_ to assess if, under our fit model, the data our likely.In other words, we - assume the model is correct- simulate new observations- check that the new observations fit with the original data | # generate trace from posterior
ppc_trace = pm.sample_posterior_predictive(trace, model=model)
# plot with data
figure(figsize=(10, 3))
plot(percentile(ppc_trace['zh'], [2.5, 97.5], axis=0).T, 'k', label=r'$z_{95\% PP}(t)$')
plot(z_t, 'r', label='$z(t)$')
legend() | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Note that - inference also estimates the initial conditions- the observed data $z(t)$ lies fully within the 95% interval of the PPC.- there are many other ways of evaluating fit Toy model 2As the next model, let's use a 2D deterministic oscillator, \begin{align}\dot{x} &= \tau (x - x^3/3 + y) \\\dot{y} &= \frac{1}{\ta... | N, τ, a, m, σ2 = 200, 3.0, 1.05, 0.2, 1e-1
xs, ys = [0.0], [1.0]
for i in range(N):
x, y = xs[-1], ys[-1]
dx = τ * (x - x**3.0/3.0 + y)
dy = (1.0 / τ) * (a - x)
xs.append(x + dt * dx + sqrt(dt) * σ2 * randn())
ys.append(y + dt * dy + sqrt(dt) * σ2 * randn())
xs, ys = array(xs), array(ys)
zs = m * xs... | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Now, estimate the hidden states $x(t)$ and $y(t)$, as well as parameters $\tau$, $a$ and $m$.As before, we rewrite our SDE as a function returned drift & diffusion coefficients: | def osc_sde(xy, τ, a):
x, y = xy[:, 0], xy[:, 1]
dx = τ * (x - x**3.0/3.0 + y)
dy = (1.0 / τ) * (a - x)
dxy = tt.stack([dx, dy], axis=0).T
return dxy, σ2 | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
As before, the Euler-Maruyama discretization of the SDE is written as a prediction of the state at step $i+1$ based on the state at step $i$. We can now write our statistical model as before, with uninformative priors on $\tau$, $a$ and $m$: | xys = c_[xs, ys]
with pm.Model() as model:
τh = pm.Uniform('τh', lower=0.1, upper=5.0)
ah = pm.Uniform('ah', lower=0.5, upper=1.5)
mh = pm.Uniform('mh', lower=0.0, upper=1.0)
xyh = EulerMaruyama('xyh', dt, osc_sde, (τh, ah), shape=xys.shape, testval=xys)
zh = pm.Normal('zh', mu=mh * xyh[:, 0] + (1 ... | Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [xyh, mh, ah, τh]
| Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Again, the result is a set of samples from the posterior, including our parameters of interest but also the hidden states | figure(figsize=(10, 6))
subplot(211)
plot(percentile(trace[xyh][..., 0], [2.5, 97.5], axis=0).T, 'k', label=r'$\hat{x}_{95\%}(t)$')
plot(xs, 'r', label='$x(t)$')
legend(loc=0)
subplot(234), hist(trace['τh']), axvline(τ), xlim([1.0, 4.0]), title('τ')
subplot(235), hist(trace['ah']), axvline(a), xlim([0, 2.0]), title('a'... | _____no_output_____ | Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Again, we can perform a posterior predictive check, that our data are likely given the fit model | # generate trace from posterior
ppc_trace = pm.sample_posterior_predictive(trace, model=model)
# plot with data
figure(figsize=(10, 3))
plot(percentile(ppc_trace['zh'], [2.5, 97.5], axis=0).T, 'k', label=r'$z_{95\% PP}(t)$')
plot(zs, 'r', label='$z(t)$')
legend()
%load_ext watermark
%watermark -n -u -v -iv -w | scipy 1.4.1
logging 0.5.1.2
matplotlib.pylab 1.18.5
re 2.2.1
pymc3 3.9.0
matplotlib 3.2.1
numpy 1.18.5
arviz 0.8.3
last updated: Mon Jun 15 2020
CPython 3.7.7
IPython 7.15.0
watermark 2.0.2
| Apache-2.0 | docs/source/notebooks/Euler-Maruyama_and_SDEs.ipynb | satrio-hw/pymc3 |
Introdução a linguagem Python (parte 1)Notebook para o curso de IoT - IFSP PiracicabaGustavo Voltani von AtzingenPython - versão 2.7Este notebook contém uma introdução aos comandos básicos em python.Serão cobertos os seguintes tópicos* Print* Comentários* Atribuição de variáveis e tipos* Trabalhando com strings (parte... | print "Hello Python 2.7 !" | Hello Python 2.7 !
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Também podemos imprimir várias strings ou numeros, separando-os por ',' | print 'Parte 1 - ', ' A resposta é: ', 42 | Parte 1 - A resposta é: 42
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Podemos inserir variáveis (núméricas) no meio do texto utilizando o método .format | print 'O valor da leitura dos sensores são {}Votls e {}Volts'.format(4.2, 1.68) | O valor da leitura dos sensores são 4.2Votls e 1.68Volts
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
ComentáriosComentários são inseridos no programa utilizando o caracter '' e com isso toda linha é ignorada pelo interpretador | # isto é uma linha de comentário | _____no_output_____ | MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Para fazer um bloco de comentário (várias linhas), utiliza-se ''' no início e ''' no final do bloco de comentário | ''' Isto e um bloco de comentarios
Todas as linhas neste bloco sao ignoradas
pelo interpretador
''' | _____no_output_____ | MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Atribuição de variáveis Em python as variáveis não são explicitamente declaradas. O interpretador faz a atribuição em tempo de execução. Os tipis de estrutura utilizadas pelo interpretador são:* Números (number) - Inteiro ou real* Strings (string)* Listas (list)* Tuplas (tuple)* Dicionários (dictionary) | a = 42 # A variável á recebe um número
b = 1.68 # Variável real
c = 'texto' # Texto
print a, b, c | 42 1.68 texto
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
As variáveis podem alterar o seu tipo durante a execução (runtime) | a = 1.3
print 'valor de a antes: ', a
a = 'texto'
print 'valor de a depois: ', a | valor de a antes: 1.3
valor de a depois: texto
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
As variáveis podem sem atribuidas simultaneamente. Isto pode ser feito para simplificar o código e evitar a criação de variáveis temporárias | a, b = 1, 1
print a, b
a, b = b, a + b
print a, b | 1 1
1 2
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Strings strings podem ser criadas utilizando ' ou " (aspas simples ou dupla) | nome = 'Gustavo' # Isto é uma string
nome = "Joao" # Isto também é uma string
letra = 'a' # Strings também podem ter um único caracter | _____no_output_____ | MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Podemos utilizar a indexação para acessar elementos da string ou partes dela | nome = 'Gustavo Voltani von Atzingen'
print nome[0], nome[1], nome[8] # A indexação começa em zero e segue até o ultimo valor
nome = 'Gustavo Voltani von Atzingen'
print nome[-1], nome[-2] # Também existe a indexação do fim para o início com
#números negativos iniciando em 1
nome = 'Gustavo V... | Voltani
Atzingen
Gustavo
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Existes vários métodos que podem ser aplicados na string. O método split divide a string em um caracter especificado. Outros métidis serão abordados em aulas posteriores. | nome = 'Gustavo Voltani von Atzingen'
print nome.split(' ') # separando o nome pelo espaço em branco | ['Gustavo', 'Voltani', 'von', 'Atzingen']
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Listas Listas são sequencias ordenadas de objetos (que podem ser strings, numeros, listas ou outros) | lista = ['texto1', 'texto2', 'texto3', 'texto4']
print lista
# também podemos ter vários tipos na mesma lista
lista = [42, 'texto2', 1.68, 'texto4']
print lista
# também podemos ter uma lista dentro de outra
lista = [ [42, 54, 1.7], 'texto2', 1.68, 'texto4']
print lista
# A lista também é indexada e pode ser buscada... | 42 34 [78, 1, 91]
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Estruturas de controle: if | a = 4
if a < 1:
print 'a é menor que 1'
elif a < 3:
print 'a é menor que 3 e maior ou igual 1'
elif a < 5:
print 'a é menor que 5 e maior ou igual 3'
else:
print 'a é maior= 5' | a é menor que 5 e maior ou igual 3
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Estruturas de controle: for for é uma estrutura de controle que vai iterar sobre uma lista ou uma string | nome = 'gustavo'
for letra in nome:
print letra
lista = ['texto1', 'texto2', 'texto3', 'texto4']
for item in lista:
print item
# Se quisermos fazer uma repetição com contagem numérica, podemos
# utilizar a função range() ou outras que serão mostradas futuramente
# Mostra os números de 0 a 9
for i in range(10):... | 0 texto1
1 texto2
2 texto3
3 texto4
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Estruturas de while: for Repete até que a condição seja falsa | contador = 0
while contador < 5:
print contador
contador += 1 | 0
1
2
3
4
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Funções Funções são escritas com a palavra def e o nome da função, juntamente com os argumentos.Pode retorar (ou não) um ou mais ojbetos. | def somador(a, b):
return a + a
somador(1, 2)
def separa_por_espao(texto):
if ' ' in texto:
return texto.split(' ')
else:
return None
nome1, nome2 = separa_por_espao('nome1 nome2')
print nome1, nome2
# funções podem ter argumentos chave
def soma(a, b=1):
return a + b
print soma(1... | 3
2
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
Módulos e importação | import datetime
tempo_atual = datetime.datetime.now()
print tempo_atual.hour, tempo_atual.minute, tempo_atual.second
from datetime import datetime as d
tempo_atual = d.now()
print tempo_atual.hour, tempo_atual.minute, tempo_atual.second | 16 26 42
| MIT | aula-03-python/.ipynb_checkpoints/Introducao-Python-01-checkpoint.ipynb | Atzingen/curso-IoT-2017 |
计算机视觉作为一门让机器学会如何去“看”的学科,具体的说,就是让机器去识别摄像机拍摄的图片或视频中的物体,检测出物体所在的位置,并对目标物体进行跟踪,从而理解并描述出图片或视频里的场景和故事,以此来模拟人脑视觉系统。因此,计算机视觉也通常被叫做机器视觉,其目的是建立能够从图像或者视频中“感知”信息的人工系统。计算机视觉技术经过几十年的发展,已经在交通(车牌识别、道路违章抓拍)、安防(人脸闸机、小区监控)、金融(刷脸支付、柜台的自动票据识别)、医疗(医疗影像诊断)、工业生产(产品缺陷自动检测)等多个领域应用,影响或正在改变人们的日常生活和工业生产方式。未来,随着技术的不断演进,必将涌现出更多的产品和应用,为我们的生活创造更大的便利和更... | import matplotlib.pyplot as plt
import numpy as np
import paddle
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
%matplotlib inline
# 创建初始化权重参数w
w = np.array([1, 0, -1], dtype='float32')
# 将权重参数调整成维度为[cout, cin, kh, kw]的四维张量
w = w.reshape([1, 1, 1, 3])
# 创建卷积算子,设置输出通道数,卷积核大小,和初始化权重参数
# kernel_siz... | Parameter containing:
Tensor(shape=[1, 1, 1, 3], dtype=float32, place=CUDAPlace(0), stop_gradient=False,
[[[[ 1., 0., -1.]]]])
Parameter containing:
Tensor(shape=[1], dtype=float32, place=CUDAPlace(0), stop_gradient=False,
[0.])
| Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
**案例2——图像中物体边缘检测**上面展示的是一个人为构造出来的简单图片,使用卷积网络检测图片明暗分界处的示例。对于真实的图片,也可以使用合适的卷积核(3\*3卷积核的中间值是8,周围一圈的值是8个-1)对其进行操作,用来检测物体的外形轮廓,观察输出特征图跟原图之间的对应关系,如下代码所示: | import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import paddle
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
img = Image.open('./work/images/section1/000000098520.jpg')
# 设置卷积核参数
w = np.array([[-1,-1,-1], [-1,8,-1], [-1,-1,-1]], dtype='float32')/8
w = w.reshape([1, 1, 3,... | _____no_output_____ | Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
**案例3——图像均值模糊**另外一种比较常见的卷积核(5\*5的卷积核中每个值均为1)是用当前像素跟它邻域内的像素取平均,这样可以使图像上噪声比较大的点变得更平滑,如下代码所示: | import paddle
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from paddle.nn import Conv2D
from paddle.nn.initializer import Assign
# 读入图片并转成numpy.ndarray
# 换成灰度图
img = Image.open('./work/images/section1/000000355610.jpg').convert('L')
img = np.array(img)
# 创建初始化参数
w = np.ones([1, 1, 5, 5], dt... | _____no_output_____ | Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
池化(Pooling)池化是使用某一位置的相邻输出的总体统计特征代替网络在该位置的输出,其好处是当输入数据做出少量平移时,经过池化函数后的大多数输出还能保持不变。比如:当识别一张图像是否是人脸时,我们需要知道人脸左边有一只眼睛,右边也有一只眼睛,而不需要知道眼睛的精确位置,这时候通过池化某一片区域的像素点来得到总体统计特征会显得很有用。由于池化之后特征图会变得更小,如果后面连接的是全连接层,能有效的减小神经元的个数,节省存储空间并提高计算效率。如 **图15** 所示,将一个$2\times 2$的区域池化成一个像素点。通常有两种方法,平均池化和最大池化。图15:池化 - 如图15(a):平均池化。这里使用大小为$2\times2... | # 输入数据形状是 [N, K]时的示例
import numpy as np
import paddle
from paddle.nn import BatchNorm1D
# 创建数据
data = np.array([[1,2,3], [4,5,6], [7,8,9]]).astype('float32')
# 使用BatchNorm1D计算归一化的输出
# 输入数据维度[N, K],num_features等于K
bn = BatchNorm1D(num_features=3)
x = paddle.to_tensor(data)
y = bn(x)
print('output of BatchNorm1D Laye... | output of BatchNorm1D Layer:
[[-1.2247438 -1.2247438 -1.2247438]
[ 0. 0. 0. ]
[ 1.2247438 1.2247438 1.2247438]]
std 4.0, mean 2.449489742783178,
output [-1.22474487 0. 1.22474487]
| Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
* **示例二:** 当输入数据形状是$[N, C, H, W]$时, 一般对应卷积层的输出,示例代码如下所示。这种情况下会沿着C这一维度进行展开,分别对每一个通道计算N个样本中总共$N\times H \times W$个像素点的均值和方差,数据和参数对应如下:- 输入 x, [N, C, H, W]- 输出 y, [N, C, H, W]- 均值 $\mu_B$,[C, ]- 方差 $\sigma_B^2$, [C, ]- 缩放参数$\gamma$, [C, ]- 平移参数$\beta$, [C, ]------**小窍门:**可能有读者会问:“BatchNorm里面不是还要对标准化之后的结果做仿射变换吗,怎么使用Numpy计算... | # 输入数据形状是[N, C, H, W]时的batchnorm示例
import numpy as np
import paddle
from paddle.nn import BatchNorm2D
# 设置随机数种子,这样可以保证每次运行结果一致
np.random.seed(100)
# 创建数据
data = np.random.rand(2,3,3,3).astype('float32')
# 使用BatchNorm2D计算归一化的输出
# 输入数据维度[N, C, H, W],num_features等于C
bn = BatchNorm2D(num_features=3)
x = paddle.to_tensor(d... | input of BatchNorm2D Layer:
[[[[0.54340494 0.2783694 0.4245176 ]
[0.84477615 0.00471886 0.12156912]
[0.67074907 0.82585275 0.13670659]]
[[0.5750933 0.89132196 0.20920213]
[0.18532822 0.10837689 0.21969749]
[0.9786238 0.8116832 0.17194101]]
[[0.81622475 0.27407375 0.4317042 ]
[0.9400298 0.817... | Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
**- 预测时使用BatchNorm**上面介绍了在训练过程中使用BatchNorm对一批样本进行归一化的方法,但如果使用同样的方法对需要预测的一批样本进行归一化,则预测结果会出现不确定性。例如样本A、样本B作为一批样本计算均值和方差,与样本A、样本C和样本D作为一批样本计算均值和方差,得到的结果一般来说是不同的。那么样本A的预测结果就会变得不确定,这对预测过程来说是不合理的。解决方法是在训练过程中将大量样本的均值和方差保存下来,预测时直接使用保存好的值而不再重新计算。实际上,在BatchNorm的具体实现中,训练时会计算均值和方差的移动平均值。在飞桨中,默认是采用如下方式计算:$$saved\_\mu_B \leftarrow \... | # dropout操作
import paddle
import numpy as np
# 设置随机数种子,这样可以保证每次运行结果一致
np.random.seed(100)
# 创建数据[N, C, H, W],一般对应卷积层的输出
data1 = np.random.rand(2,3,3,3).astype('float32')
# 创建数据[N, K],一般对应全连接层的输出
data2 = np.arange(1,13).reshape([-1, 3]).astype('float32')
# 使用dropout作用在输入数据上
x1 = paddle.to_tensor(data1)
# downgrade_in_i... | _____no_output_____ | Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
从上述代码的输出可以发现,经过dropout之后,tensor中的某些元素变为了0,这个就是dropout实现的功能,通过随机将输入数据的元素置0,消除减弱了神经元节点间的联合适应性,增强模型的泛化能力。 小结学习完这些概念,您就具备了搭建卷积神经网络的基础。下一节,我们将应用这些基础模块,一起完成图像分类中的典型应用 — 医疗图像中的眼疾筛查任务的模型搭建。 作业 1 计算卷积中一共有多少次乘法和加法操作输入数据形状是$[10, 3, 224, 224]$,卷积核$k_h = k_w = 3$,输出通道数为$64$,步幅$stride=1$,填充$p_h = p_w = 1$。则完成这样一个卷积,一共需要做多少次乘法和加法操作... | # 定义 SimpleNet 网络结构
import paddle
from paddle.nn import Conv2D, MaxPool2D, Linear
import paddle.nn.functional as F
class SimpleNet(paddle.nn.Layer):
def __init__(self, num_classes=1):
#super(SimpleNet, self).__init__(name_scope)
self.conv1 = Conv2D(in_channels=3, out_channels=6, kernel_size=5, stri... | _____no_output_____ | Apache-2.0 | junior_class/chapter-3-Computer_Vision/notebook/3-1-CV-CNN_Basis.ipynb | CS-Learnings/PaddlePaddle-awesome-DeepLearning |
Transfer Learning Template | %load_ext autoreload
%autoreload 2
%matplotlib inline
import os, json, sys, time, random
import numpy as np
import torch
from torch.optim import Adam
from easydict import EasyDict
import matplotlib.pyplot as plt
from steves_models.steves_ptn import Steves_Prototypical_Network
from steves_utils.lazy_iterable_wr... | _____no_output_____ | MIT | experiments/tl_1v2/wisig-oracle.run1.limited/trials/16/trial.ipynb | stevester94/csc500-notebooks |
Allowed ParametersThese are allowed parameters, not defaultsEach of these values need to be present in the injected parameters (the notebook will raise an exception if they are not present)Papermill uses the cell tag "parameters" to inject the real parameters below this cell.Enable tags to see what I mean | required_parameters = {
"experiment_name",
"lr",
"device",
"seed",
"dataset_seed",
"n_shot",
"n_query",
"n_way",
"train_k_factor",
"val_k_factor",
"test_k_factor",
"n_epoch",
"patience",
"criteria_for_best",
"x_net",
"datasets",
"torch_default_dtype",
... | _____no_output_____ | MIT | experiments/tl_1v2/wisig-oracle.run1.limited/trials/16/trial.ipynb | stevester94/csc500-notebooks |
**This notebook is an exercise in the [Data Cleaning](https://www.kaggle.com/learn/data-cleaning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/parsing-dates).**--- In this exercise, you'll apply what you learned in the **Parsing dates** tutorial. SetupThe questions below wil... | from learntools.core import binder
binder.bind(globals())
from learntools.data_cleaning.ex3 import *
print("Setup Complete") | Setup Complete
| MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
Get our environment set upThe first thing we'll need to do is load in the libraries and dataset we'll be using. We'll be working with a dataset containing information on earthquakes that occured between 1965 and 2016. | # modules we'll use
import pandas as pd
import numpy as np
import seaborn as sns
import datetime
# read in our data
earthquakes = pd.read_csv("../input/earthquake-database/database.csv")
# set seed for reproducibility
np.random.seed(0) | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
1) Check the data type of our date columnYou'll be working with the "Date" column from the `earthquakes` dataframe. Investigate this column now: does it look like it contains dates? What is the dtype of the column? | # TODO: Your code here!
earthquakes['Date'].dtype | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
Once you have answered the question above, run the code cell below to get credit for your work. | # Check your answer (Run this code cell to receive credit!)
q1.check()
# Line below will give you a hint
#q1.hint() | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
2) Convert our date columns to datetimeMost of the entries in the "Date" column follow the same format: "month/day/four-digit year". However, the entry at index 3378 follows a completely different pattern. Run the code cell below to see this. | earthquakes[3378:3383] | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
This does appear to be an issue with data entry: ideally, all entries in the column have the same format. We can get an idea of how widespread this issue is by checking the length of each entry in the "Date" column. | date_lengths = earthquakes.Date.str.len()
date_lengths.value_counts() | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
Looks like there are two more rows that has a date in a different format. Run the code cell below to obtain the indices corresponding to those rows and print the data. | indices = np.where([date_lengths == 24])[1]
print('Indices with corrupted data:', indices)
earthquakes.loc[indices] | Indices with corrupted data: [ 3378 7512 20650]
| MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
Given all of this information, it's your turn to create a new column "date_parsed" in the `earthquakes` dataset that has correctly parsed dates in it. **Note**: When completing this problem, you are allowed to (but are not required to) amend the entries in the "Date" and "Time" columns. Do not remove any rows from th... | # TODO: Your code here
date_format = '%m/%d/%Y'
earthquakes.loc[indices,'Date'] = pd.to_datetime(earthquakes.loc[indices,'Date']) \
.dt.strftime(date_format)
earthquakes['date_parsed'] = pd.to_datetime(earthquakes['Date'])
# Check your answer
q2.check()
# Lines below will give you a ... | _____no_output_____ | MIT | data_cleaning/03-parsing-dates.ipynb | drakearch/kaggle-courses |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.