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
One hot encodingURL: https://hackernoon.com/what-is-one-hot-encoding-why-and-when-do-you-have-to-use-it-e3c6186d008f
# one hot encoding kut_onehot = pd.get_dummies(kut_venues[['Venue Category']], prefix="", prefix_sep="") # add neighborhood column back to dataframe kut_onehot['Neighborhood'] = kut_venues['Neighborhood'] # move neighborhood column to the first column fixed_columns = [kut_onehot.columns[-1]] + list(kut_onehot.column...
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Grouping rows by neighborhood and by taking the mean of the frequency of occurrence of each category
kut_grouped = kut_onehot.groupby('Neighborhood').mean().reset_index() kut_grouped kut_grouped.shape num_top_venues = 5 for hood in kut_grouped['Neighborhood']: print("----"+hood+"----") temp = kut_grouped[kut_grouped['Neighborhood'] == hood].T.reset_index() temp.columns = ['venue','freq'] temp = temp.i...
----Berrylands---- venue freq 0 Bus Stop 0.25 1 Gym / Fitness Center 0.25 2 Park 0.25 3 Café 0.25 4 Pub 0.00 ----Canbury---- venue freq 0 Pub 0.31 1 Park 0.08 2 Hotel ...
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Create a data frame of the venues Function to sort the venues in descending order.
def return_most_common_venues(row, num_top_venues): row_categories = row.iloc[1:] row_categories_sorted = row_categories.sort_values(ascending=False) return row_categories_sorted.index.values[0:num_top_venues]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Create the new dataframe and display the top 10 venues for each neighborhood
num_top_venues = 10 indicators = ['st', 'nd', 'rd'] # create columns according to number of top venues columns = ['Neighborhood'] for ind in np.arange(num_top_venues): try: columns.append('{}{} Most Common Venue'.format(ind+1, indicators[ind])) except: columns.append('{}th Most Common Venue'.f...
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Clustering similar neighborhoods together using k - means clustering
# import k-means from clustering stage from sklearn.cluster import KMeans # set number of clusters kclusters = 5 kut_grouped_clustering = kut_grouped.drop('Neighborhood', 1) # run k-means clustering kmeans = KMeans(n_clusters=kclusters, random_state=0).fit(kut_grouped_clustering) # check cluster labels generated fo...
<class 'pandas.core.frame.DataFrame'> Int64Index: 14 entries, 0 to 14 Data columns (total 15 columns): Neighborhood 14 non-null object Borough 14 non-null object Latitude 14 non-null float64 Longitude 14 non-null float64 Cluster Labels 14 non-nu...
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Visualize the clusters
# create map map_clusters = folium.Map(location=[latitude, longitude], zoom_start=11.5) # set color scheme for the clusters x = np.arange(kclusters) ys = [i + x + (i*x)**2 for i in range(kclusters)] colors_array = cm.rainbow(np.linspace(0, 1, len(ys))) rainbow = [colors.rgb2hex(i) for i in colors_array] # add markers...
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Each cluster is color coded for the ease of presentation, we can see that majority of the neighborhood falls in the red cluster which is the first cluster. Three neighborhoods have their own cluster (Blue, Purple and Yellow), these are clusters two three and five. The green cluster consists of two neighborhoods which i...
kut_merged[kut_merged['Cluster Labels'] == 0]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
The cluster one is the biggest cluster with 9 of the 15 neighborhoods in the borough Kingston upon Thames. Upon closely examining these neighborhoods we can see that the most common venues in these neighborhoods are Restaurants, Pubs, Cafe, Supermarkets, and stores. Examine the second cluster
kut_merged[kut_merged['Cluster Labels'] == 1]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
The second cluster has one neighborhood which consists of Venues such as Restaurants, Golf courses, and wine shops. Examine the third cluster
kut_merged[kut_merged['Cluster Labels'] == 2]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
The third cluster has one neighborhood which consists of Venues such as Train stations, Restaurants, and Furniture shops. Examine the forth cluster
kut_merged[kut_merged['Cluster Labels'] == 3]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
The fourth cluster has two neighborhoods in it, these neighborhoods have common venues such as Parks, Gym/Fitness centers, Bus Stops, Restaurants, Electronics Stores and Soccer fields etc. Examine the fifth cluster
kut_merged[kut_merged['Cluster Labels'] == 4]
_____no_output_____
MIT
Capstone Project - The Battle of the Neighborhoods - London Neighborhood Clustering.ipynb
ZRQ-rikkie/coursera-python
Creating your own dataset from Google Images*by: Francisco Ingham and Jeremy Howard. Inspired by [Adrian Rosebrock](https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/)* In this tutorial we will see how to easily create an image dataset through Google Images. **Note**: Y...
from fastai.vision import *
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Get a list of URLs Search and scroll Go to [Google Images](http://images.google.com) and search for the images you are interested in. The more specific you are in your Google Search, the better the results and the less manual pruning you will have to do.Scroll down until you've seen all the images you want to downloa...
folder = 'black' file = 'urls_black.txt' folder = 'teddys' file = 'urls_teddys.txt' folder = 'grizzly' file = 'urls_grizzly.txt'
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
You will need to run this cell once per each category.
path = Path('data/bears') dest = path/folder dest.mkdir(parents=True, exist_ok=True) path.ls()
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Finally, upload your urls file. You just need to press 'Upload' in your working directory and select your file, then click 'Upload' for each of the displayed files.![uploaded file](images/download_images/upload.png) Download images Now you will need to download your images from their respective urls.fast.ai has a func...
classes = ['teddys','grizzly','black'] download_images(path/file, dest, max_pics=200) # If you have problems download, try with `max_workers=0` to see exceptions: download_images(path/file, dest, max_pics=20, max_workers=0)
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Then we can remove any images that can't be opened:
for c in classes: print(c) verify_images(path/c, delete=True, max_size=500)
teddys
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
View data
np.random.seed(42) data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.2, ds_tfms=get_transforms(), size=224, num_workers=4).normalize(imagenet_stats) # If you already cleaned your data, run this cell instead of the one before # np.random.seed(42) # data = ImageDataBunch.from_csv(".", folder=".", val...
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Good! Let's take a look at some of our pictures then.
data.classes data.show_batch(rows=3, figsize=(7,8)) data.classes, data.c, len(data.train_ds), len(data.valid_ds)
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Train model
learn = cnn_learner(data, models.resnet34, metrics=error_rate) learn.fit_one_cycle(4) learn.save('stage-1') learn.unfreeze() learn.lr_find() learn.recorder.plot() learn.fit_one_cycle(2, max_lr=slice(3e-5,3e-4)) learn.save('stage-2')
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Interpretation
learn.load('stage-2'); interp = ClassificationInterpretation.from_learner(learn) interp.plot_confusion_matrix()
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Cleaning UpSome of our top losses aren't due to bad performance by our model. There are images in our data set that shouldn't be.Using the `ImageCleaner` widget from `fastai.widgets` we can prune our top losses, removing photos that don't belong.
from fastai.widgets import *
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
First we need to get the file paths from our top_losses. We can do this with `.from_toplosses`. We then feed the top losses indexes and corresponding dataset to `ImageCleaner`.Notice that the widget will not delete images directly from disk but it will create a new csv file `cleaned.csv` from where you can create a new...
ds, idxs = DatasetFormatter().from_toplosses(learn, ds_type=DatasetType.Valid) ImageCleaner(ds, idxs, path)
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Flag photos for deletion by clicking 'Delete'. Then click 'Next Batch' to delete flagged photos and keep the rest in that row. `ImageCleaner` will show you a new row of images until there are no more to show. In this case, the widget will show you images until there are none left from `top_losses.ImageCleaner(ds, idxs)...
ds, idxs = DatasetFormatter().from_similars(learn, ds_type=DatasetType.Valid) ImageCleaner(ds, idxs, path, duplicates=True)
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Remember to recreate your ImageDataBunch from your `cleaned.csv` to include the changes you made in your data! Putting your model in production First thing first, let's export the content of our `Learner` object for production:
learn.export()
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
This will create a file named 'export.pkl' in the directory where we were working that contains everything we need to deploy our model (the model, the weights but also some metadata like the classes or the transforms/normalization used). You probably want to use CPU for inference, except at massive scale (and you almos...
defaults.device = torch.device('cpu') img = open_image(path/'black'/'00000021.jpg') img
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
We create our `Learner` in production enviromnent like this, jsut make sure that `path` contains the file 'export.pkl' from before.
learn = load_learner(path) pred_class,pred_idx,outputs = learn.predict(img) pred_class
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
So you might create a route something like this ([thanks](https://github.com/simonw/cougar-or-not) to Simon Willison for the structure of this code):```python@app.route("/classify-url", methods=["GET"])async def classify_url(request): bytes = await get_bytes(request.query_params["url"]) img = open_image(BytesIO(b...
learn = cnn_learner(data, models.resnet34, metrics=error_rate) learn.fit_one_cycle(1, max_lr=0.5)
Total time: 00:13 epoch train_loss valid_loss error_rate 1 12.220007 1144188288.000000 0.765957 (00:13)
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Learning rate (LR) too low
learn = cnn_learner(data, models.resnet34, metrics=error_rate)
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Previously we had this result:```Total time: 00:57epoch train_loss valid_loss error_rate1 1.030236 0.179226 0.028369 (00:14)2 0.561508 0.055464 0.014184 (00:13)3 0.396103 0.053801 0.014184 (00:13)4 0.316883 0.050197 0.021277 (00:15)```
learn.fit_one_cycle(5, max_lr=1e-5) learn.recorder.plot_losses()
_____no_output_____
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
As well as taking a really long time, it's getting too many looks at each image, so may overfit. Too few epochs
learn = cnn_learner(data, models.resnet34, metrics=error_rate, pretrained=False) learn.fit_one_cycle(1)
Total time: 00:14 epoch train_loss valid_loss error_rate 1 0.602823 0.119616 0.049645 (00:14)
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Too many epochs
np.random.seed(42) data = ImageDataBunch.from_folder(path, train=".", valid_pct=0.9, bs=32, ds_tfms=get_transforms(do_flip=False, max_rotate=0, max_zoom=1, max_lighting=0, max_warp=0 ),size=224, num_workers=4).normalize(imagenet_stats) learn = cnn_learner(data, models.resnet50, me...
Total time: 06:39 epoch train_loss valid_loss error_rate 1 1.513021 1.041628 0.507326 (00:13) 2 1.290093 0.994758 0.443223 (00:09) 3 1.185764 0.936145 0.410256 (00:09) 4 1.117229 0.838402 0.322344 (00:09) 5 1.022635 0.734872 0.252747 (00:09) 6 ...
Apache-2.0
nbs/dl1/lesson2-download.ipynb
technophile21/course-v3
Tutorial: LIF Neuron - Part I**Week 0, Day 1: Python Workshop 1****By Neuromatch Academy**__Content creators:__ Marco Brigham and the [CCNSS](https://www.ccnss.org/) team__Content reviewers:__ Michael Waskom, Karolina Stosio, Spiros Chavlis --- Tutorial objectivesNMA students, you are going to use Python skills to ad...
# Import libraries import numpy as np import matplotlib.pyplot as plt from IPython.display import YouTubeVideo # @title Figure settings %config InlineBackend.figure_format = 'retina' plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
--- Neuron modelA *membrane equation* and a *reset condition* define our *leaky-integrate-and-fire (LIF)* neuron:\begin{align*}\\&\tau_m\,\frac{d}{dt}\,V(t) = E_{L} - V(t) + R\,I(t) &\text{if }\quad V(t) \leq V_{th}\\\\&V(t) = V_{reset} &\text{otherwise}\\\\\end{align*}where $V(t)$ is the membrane potential, $\tau_m$ i...
# @title Video: Synaptic input video = YouTubeVideo(id='UP8rD2AwceM', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 1We start by defining and initializing the main simulation variables.**Suggestions*** Modify the code below to print the simulation parameters
# t_max = 150e-3 # second # dt = 1e-3 # second # tau = 20e-3 # second # el = -60e-3 # milivolt # vr = -70e-3 # milivolt # vth = -50e-3 # milivolt # r = 100e6 # ohm # i_mean = 25e-11 # ampere # print(t_max, dt, tau, el, vr, vth, r, i_mean)
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
**SAMPLE OUTPUT**```0.15 0.001 0.02 -0.06 -0.07 -0.05 100000000.0 2.5e-10``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_4adeccd3.py) Exercise 2![synaptic input](https://github.com/mpbrigham/colaboratory-figure...
# initialize t t = 0 # loop for 10 steps, variable 'step' takes values from 0 to 9 for step in range(10): t = step * dt i = ... print(i)
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
**SAMPLE OUTPUT**```2.5e-103.969463130731183e-104.877641290737885e-104.877641290737885e-103.9694631307311837e-102.5000000000000007e-101.0305368692688176e-101.2235870926211617e-111.223587092621159e-111.0305368692688186e-10``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutoria...
# initialize step_end step_end = 10 # loop for step_end steps for step in range(step_end): t = step * dt i = ... print(...)
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
**SAMPLE OUTPUT**```0.000 2.5000e-100.001 3.9695e-100.002 4.8776e-100.003 4.8776e-100.004 3.9695e-100.005 2.5000e-100.006 1.0305e-100.007 1.2236e-110.008 1.2236e-110.009 1.0305e-10``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tu...
# @title Video: Discrete time integration video = YouTubeVideo(id='kyCbeR28AYQ', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 4Compute the values of $V(t)$ between $t=0$ and $t=0.01$ with step $\Delta t=0.001$ and $V(0)=E_L$.We will write a `for` loop from scratch in this exercise. The following three formulations are all equivalent and loop for three steps:```for step in [0, 1, 2]: print(step)for step in range(3): print(step)star...
# initialize step_end and v step_end = 10 v = el # loop for step_end steps for step in range(step_end): t = step * dt i = ... print(...) v = ...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
**SAMPLE OUTPUT**```0.000 -6.0000e-020.001 -5.8750e-020.002 -5.6828e-020.003 -5.4548e-020.004 -5.2381e-020.005 -5.0778e-020.006 -4.9989e-020.007 -4.9974e-020.008 -5.0414e-020.009 -5.0832e-02``` [*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutio...
# @title Video: Plotting from IPython.display import YouTubeVideo video = YouTubeVideo(id='BOh8CsuTFkY', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 5![synaptic input discrete](https://github.com/mpbrigham/colaboratory-figures/raw/master/nma/python-for-nma/synaptic_input_discrete.png)Plot the values of $I(t)$ between $t=0$ and $t=0.024$.**Suggestions*** Increase `step_end`* initialize the figure with `plt.figure`, set title, x and y labels with `plt.title...
# initialize step_end step_end = 25 # initialize the figure plt.figure() # Complete these lines and uncomment # plt.title(...) # plt.xlabel(...) # plt.ylabel(...) # loop for step_end steps for step in range(step_end): t = step * dt i = ... # Complete this line and uncomment # plt.plot(...) # plt.show()
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_23446a7e.py)*Example output:* Exercise 6Plot the values of $V(t)$ between $t=0$ and $t=t_{max}$.**Suggestions*** Compute the required number of steps with`int(t_max/d...
# initialize step_end and v step_end = int(t_max / dt) v = el # initialize the figure plt.figure() plt.title('$V_m$ with sinusoidal I(t)') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)'); # loop for step_end steps for step in range(step_end): t = step * dt i = ... # Complete this line and uncomment # plt.plot(...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_1046fd94.py)*Example output:* --- Random synaptic inputFrom the perspective of neurons, synaptic input is random (or stochastic). We'll improve the synaptic input mode...
# set random number generator np.random.seed(2020) # initialize step_end and v step_end = int(t_max / dt) v = el # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') # loop for step_end steps for step in range(step_end): t = step * dt # Complete ...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_41355f96.py)*Example output:* Ensemble statisticsMultiple runs of the previous exercise may give the impression of periodic regularity in the evolution of $V(t)$. We'...
# @title Video: Ensemble statistics video = YouTubeVideo(id='4nIAS2oPEFI', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 8Plot multiple realizations ($N=50$) of $V(t)$ by storing in a list the voltage of each neuron at time $t$.Keep in mind that the plotting command `plt.plot(x, y)` requires `x` to have the same number of elements as `y`.Mathematical symbols such as $\alpha$ and $\beta$ are specified as `$\alpha$` and `$\beta$`...
# set random number generator np.random.seed(2020) # initialize step_end, n and v_n step_end = int(t_max / dt) n = 50 # Complete this line and uncomment # v_n = ... # initialize the figure plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') # loop for step_end step...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_8b55f5dd.py)*Example output:* Exercise 9Add the sample mean $\left\langle V(t)\right\rangle=\frac{1}{N}\sum_{n=1}^N V_n(t)$ to the plot.**Suggestions*** At each times...
# set random number generator np.random.seed(2020) # initialize step_end, n and v_n step_end = int(t_max / dt) n = 50 v_n = [el] * n # initialize the figure plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') # loop for step_end steps for step in range(step_end): ...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_98017570.py)*Example output:* Exercise 10Add the sample standard deviation $\sigma(t)\equiv\sqrt{\text{Var}\left(t\right)}$ to the plot, with sample variance $\text{V...
# set random number generator np.random.seed(2020) # initialize step_end, n and v_n step_end = int(t_max / dt) n = 50 v_n = [el] * n # initialize the figure plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') # loop for step_end steps for step in range(step_end): ...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_9e048e4b.py)*Example output:* --- Using NumPyThe next set of exercises introduces `np.array`, the workhorse from the scientific computation package [NumPy](https://num...
# @title Video: Using NumPy video = YouTubeVideo(id='ewyHKKa2_OU', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 11Rewrite the single neuron plot with random input from _Exercise 7_ with numpy arrays. The time range, voltage values, and synaptic current are initialized or pre-computed as numpy arrays before numerical integration.**Suggestions*** Use `np.linspace` to initialize a numpy array `t_range` with `num=step_end=...
# set random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max / dt) - 1 # skip the endpoint to match Exercise 7 plot t_range = np.linspace(0, t_max, num=step_end, endpoint=False) v = el * np.ones(step_end) syn = ... # loop for step_end - 1 steps # Complete these lin...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_4427a815.py)*Example output:* Exercise 12Let's practice using `enumerate` to iterate over the indexes and values of the synaptic current array `syn`.**Suggestions*** ...
# set random number generator np.random.seed(2020) # initialize step_end, t_range, v and syn step_end = int(t_max / dt) t_range = np.linspace(0, t_max, num=step_end) v = el * np.ones(step_end) syn = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random(step_end) - 1)) # loop for step_end values of syn for s...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_4139f63a.py)*Example output:*
# @title Video: Aggregation video = YouTubeVideo(id='1ME-0rJXLFg', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
Exercise 13Plot multiple realizations ($N=50$) of $V(t)$ by storing the voltage of each neuron at time $t$ in a numpy array.**Suggestions*** Initialize a numpy array `v_n` of shape `(n, step_end)` with membrane leak potential values `el`* Pre-compute synaptic current values in numpy array `syn` of shape `(n, step_end)...
# set random number generator np.random.seed(2020) # initialize step_end, n, t_range, v and syn step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) syn = ... # loop for step_end - 1 steps # Complete these lines and uncomment # for step in range(1, step_end...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W0D1_PythonWorkshop1/solutions/W0D1_Tutorial1_Solution_e8466b6b.py)*Example output:* Exercise 14Add sample mean $\left\langle V(t)\right\rangle$ and standard deviation $\sigma(t)\equiv\sqrt{\text{Var}\left(t\right)}$ to t...
# set random number generator np.random.seed(2020) # initialize step_end, n, t_range, v and syn step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) syn = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random([n, step_end]) - 1)) # loop for step_e...
_____no_output_____
CC-BY-4.0
tutorials/W0D1_PythonWorkshop1/student/W0D1_Tutorial1.ipynb
bgalbraith/course-content
¿Cómo crece una población? Antes de empezar: llenar la siguiente encuesta.- https://forms.office.com/Pages/ResponsePage.aspx?id=8kgDb5jkyUWE9MbYHc_9_oplb4UZe4dMnU4bxi5xU55UQjlEQ1pLWElPOE9ON082RktFQVdRWEtPSS4u> El modelo más simple de crecimiento poblacional de organismos es $\frac{dx}{dt}=rx$, donde $x(t)$ es la pobl...
# Importar librerías necesarias # Definir función mu(x) # Graficar
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
___Entonces, con esta elección de $\mu(x)=r(1-x)$, obtenemos la llamada **ecuación lógistica**, publicada por Pierre Verhulst en 1838.$$\frac{dx}{dt} = r\; x\; (1- x)$$ ** Solución a la ecuación diferencial ** La ecuación diferencial inicial tiene *solución analítica*, $$ x(t) = \frac{1}{1+ (\frac{1}{x_{0}}- 1) e^{-rt}...
# Definir la solución analítica x(t,x0) # Vector de tiempo # Condicion inicial # Graficar para diferentes r entre -1 y 1
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
Como podemos ver, la solución a está ecuación en el continuo nos puede ganantizar la extinción o bien un crecimiento descomunal, dependiendo del valor asignado a $r$. *Numéricamente*, ¿cómo resolveríamos esta ecuación?
# Importamos función para integrar numéricamente ecuaciones diferenciales # Definimos el campo de la ecuación diferencial # Parámetro r # Condición inicial # Vector de tiempo # Solución # Gráfico de la solución
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
¿Qué tan buena es la aproximación de la solución numérica?Hay ecuaciones diferenciales ordinarias no lineales para las cuales es imposible obtener la solución exacta. En estos casos, se evalúa una solución aproximada de forma numérica.Para el caso anterior fue posible obtener la solución exacta, lo cual nos permite co...
# Solución numérica # Solución exacta # Gráfica de comparación
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
Gráficamente vemos que la solución numérica está cerca (coincide) con la solución exacta. Sin embargo, con esta gráfica no podemos visualizar qué tan cerca están una solución de la otra. ¿Qué tal si evaluamos el error?
# Error de aproximación # Gráfica del error
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
Entonces, **cualitativamente** ya vimos que la solución numérica es *suficientemente buena*. De todas maneras, es siempre bueno cuantificar *qué tan buena* es la aproximación. Varias formas:- Norma del error: tenemos el error de aproximación en ciertos puntos (especificados por el vector de tiempo). Este error es enton...
np.linalg.norm(error)
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
- Error cuadrático medio: otra forma de cuantificar es con el error cuadrático medio$$e_{ms}=\frac{e[0]^2+\dots+e[n-1]^2}{n}$$
np.mean(error**2)
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
- Integral del error cuadrático: evalúa la acumulación de error cuadrático. Se puede evaluar cabo con la siguiente aproximación rectangular de la integral$$e_{is}=\int_{0}^{t_f}e(t)^2\text{d}t\approx \left(e[0]^2+\dots+e[n-1]^2\right)h$$donde $h$ es el tamaño de paso del vector de tiempo.
h = t[1]-t[0] np.sum(error**2)*h
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
Comentarios del modelo logísticoEl modelo no se debe tomar literalmente. Más bien se debe interpretar metefóricamente como que la población tiene una tendencia a crecer hasta su tope, o bien, desaparecer.La ecuación logística fue probada en experimentos de laboratorio para colonias de bacterias en condiciones de clima...
# Definición de la función mapa logístico def mapa_logistico(r, x): return r * x * (1 - x) # Para mil valores de r entre 2.0 y 4.0 n = 1000 r = np.linspace(2.0, 4.0, n) # Hacemos 1000 iteraciones y nos quedamos con las ultimas 100 (capturamos el comportamiento final) iteraciones = 1000 ultimos = 100 # La misma con...
_____no_output_____
MIT
Modulo2/.ipynb_checkpoints/Clase11_MapaLogistico-checkpoint.ipynb
ariadnagalindom/SimMat2018-2
Définition du ProblèmeLe projet consiste à prédire le vainqueur de combats entre deux pokemons.
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import csv from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score from sklearn.linear_model import LinearRegression from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import...
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Description des features NUMERO: Numero NOM: Nom du Pokemon TYPE_1: Type primaire TYPE_2: Type Secondaire POINTS_DE_VIE: Point de vie POINTS_ATTAQUE: Niveau d'attaque POINTS_DEFFENCE: Niveau de defense POINTS_ATTAQUE_SPECIALE: Niveau d'attaque spéciale POINT_DEFENSE_SPECIALE: Niveau de...
#Récupération des fichiers necessaires au modèle. import os fileList = os.listdir("./datas") for file in fileList: print(file) pokemons = pd.read_csv("./datas/pokedex.csv", encoding = "ISO-8859-1") pokemons.head(10)
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Préparation et Nettoyage des données
pokemons.shape pokemons.info() pokemons[pokemons['NOM'].isnull()] pokemons['NOM'][62]="Colossinge"
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Idenfication des features de catégorisation
cat_features = pokemons.select_dtypes(include=['object']) cat_features.head()
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Nous allons nous concentrer sur ces features à l'exception du **NOM**.
#Nombre de pokemons de type primaire #sns.catplot(x='TYPE_1',data=pokemons, kind='count', height=3, aspect=1.5) pokemons.TYPE_1.value_counts().plot.bar() #Nombre de pokemons de type secondaire pokemons.TYPE_2.value_counts().plot.bar()LEGENDAIRE pokemons.LEGENDAIRE.value_counts().plot.bar() #Transformation la feature ...
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Acquisition des données de combats
combats = pd.read_csv(".datas/combats.csv", encoding = "ISO-8859-1") combats.head() combats.columns combats.shape combats.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 50000 entries, 0 to 49999 Data columns (total 3 columns): Premier_Pokemon 50000 non-null int64 Second_Pokemon 50000 non-null int64 Pokemon_Gagnant 50000 non-null int64 dtypes: int64(3) memory usage: 1.1 MB
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Feature engineering Nous allons déterminer le nombre de combats par Pokémon. Pour cela nous devons caluler le nombre d'apparitions en premier position et le nombre de fois en seconde position.
nbreCombatsPremierePosition = combats.groupby('Premier_Pokemon').count() nbreCombatsPremierePosition.head(5) nbreCombatsSecondePosition = combats.groupby('Second_Pokemon').count() nbreCombatsSecondePosition.head(5) nbreTotalCombatsParPokemon = nbreCombatsPremierePosition+nbreCombatsSecondePosition nbreTotalCombatsParPo...
_____no_output_____
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Phase d'apprentissageIl s'agit d'un problème de regression. Nous allons utiliser les algorithmes suivants Regression Lineaire Arbre de decision Forêt aléatoire
#Modèle d'apprentissage #Algorithme de regression Lineaire algorithme = LinearRegression() #Apprentissage de l'algorithme avec des jeux de données d'apprentissage algorithme.fit(X_APPRENTISSAGE, Y_APPRENTISSAGE) #Realisation des predictions avec notre jeu de test predictions = algorithme.predict(X_VALIDATION) #Calcul ...
COMBAT OPPOSANT Mangriff A Crapustule ----------Prediction des Pokemons-------- Mangriff [0.70453906] Crapustule [0.56317528] Mangriff est vainqueur
Apache-2.0
Pokemon/Pokemon.ipynb
ISSOH/Machine-Learning
Visualise Trove newspaper searches over timeYou know the feeling. You enter a query into [Trove's digitised newspapers](https://trove.nla.gov.au/newspaper/) search box and...![Trove search results screen capture](images/trove-newspaper-results.png)Hmmm, **3 million results**, how do you make sense of that..?Trove trie...
import requests import os import ipywidgets as widgets from operator import itemgetter # used for sorting import pandas as pd # makes manipulating the data easier import altair as alt from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from tqdm.auto import tqdm from IPython...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Enter a Trove API keyWe're going to get our data from the Trove API. You'll need to get your own [Trove API key](http://help.nla.gov.au/trove/building-with-trove/api) and enter it below.
api_key = 'YOUR API KEY' print('Your API key is: {}'.format(api_key))
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
2. Find the number of articles per year using facetsWhen you search for newspaper articles using Trove's web interface, the results appear alongside a column headed 'Refine your results'. This column displays summary data extracted from your search, such as the states in which articles were published and the newspaper...
# Basic parameters for Trove API params = { 'facet': 'year', # Get the data aggregated by year. 'zone': 'newspaper', 'key': api_key, 'encoding': 'json', 'n': 0 # We don't need any records, just the facets! }
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
But what are we searching for? We need to supply a `q` parameter that includes our search terms. We can use pretty much anything that works in the Trove simple search box. This includes boolean operators, phrase searches, and proximity modifiers. But let's start with something simple. Feel free to modify the `q` value ...
# CHANGE THIS TO SEARCH FOR SOMETHING ELSE! params['q'] = 'radio'
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Let's define a couple of handy functions for getting facet data from the Trove API.
def get_results(params): ''' Get JSON response data from the Trove API. Parameters: params Returns: JSON formatted response data from Trove API ''' response = s.get('https://api.trove.nla.gov.au/v2/result', params=params, timeout=30) response.raise_for_status() # print(r...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now we'll define a function to loop through the decades, processing each in turn. To loop through the decades we need to define start and end points. Trove includes newspapers from 1803 right through until the current decade. Note that Trove expects decades to be specified using the first three digits of a year – so th...
def get_facet_data(params, start_decade=180, end_decade=201): ''' Loop throught the decades from 'start_decade' to 'end_decade', getting the number of search results for each year from the year facet. Combine all the results into a single list. Parameters: params - parameters to send to the ...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
For easy exploration, we'll convert the facet data into a [Pandas](https://pandas.pydata.org/) DataFrame.
# Convert our data to a dataframe called df df = pd.DataFrame(facet_data) # Let's have a look at the first few rows of data df.head()
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Which year had the most results? We can use `idxmax()` to find out.
# Show the row that has the highest value in the 'total_results' column. # Use .idxmax to find the row with the highest value, then use .loc to get it df.loc[df['total_results'].idxmax()]
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now let's display the data as a chart using [Altair](https://altair-viz.github.io/index.html).
alt.Chart(df).mark_line(point=True).encode( # Years on the X axis x=alt.X('year:Q', axis=alt.Axis(format='c', title='Year')), # Number of articles on the Y axis y=alt.Y('total_results:Q', axis=alt.Axis(format=',d', title='Number of articles')), # Display details when yo...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
No suprise to see a sudden increase in the use of the word 'radio' in the early decades of the 20th century, but why do the results drop away after 1954? To find out we have to dig a bit deeper into Trove. 3. How many articles in total were published each year? Ok, we've visualised a search in Trove's digitised newspa...
# Reset the 'q' parameter # Use a an empty search (a single space) to get ALL THE ARTICLES params['q'] = ' ' # Get facet data for all articles all_facet_data = get_facet_data(params)
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now let's create the chart.
# Convert the results to a dataframe df_total = pd.DataFrame(all_facet_data) # Make a chart alt.Chart(df_total).mark_line(point=True).encode( # Display the years along the X axis x=alt.X('year:Q', axis=alt.Axis(format='c', title='Year')), # Display the number of results on the Y axis ...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
This chart shows us the total number of newspaper articles in Trove for each year from 1803 to 2013. As you might expect, there's a steady increase in the number of articles published across the 19th century. But why is there such a notable peak in 1915, and why do the numbers drop away so suddenly in 1955? The answers...
def merge_df_with_total(df, df_total): ''' Merge dataframes containing search results with the total number of articles by year. This is a left join on the year column. The total number of articles will be added as a column to the existing results. Once merged, do some reorganisation and calculate ...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Let's merge!
# Merge the search results with the total articles df_merged = merge_df_with_total(df, df_total) df_merged.head()
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now we have a new dataframe `df_merged` that includes both the raw number of search results for each year, and the proportion the results represent of the total number of articles on Trove. Let's create charts for both and look at the diferences.
# This is the chart showing raw results -- it's the same as the one we created above (but a bit smaller) chart1 = alt.Chart(df).mark_line(point=True).encode( x=alt.X('year:Q', axis=alt.Axis(format='c', title='Year')), y=alt.Y('total_results:Q', axis=alt.Axis(format=',d', title='Number of articles')), ...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
The overall shape of the two charts is similar, but there are some significant differences. Both show a dramatic increase after 1920, but the initial peaks are in different positions. The sudden drop-off after 1954 has gone, and we even have a new peak in 1963. Why 1963? The value of these sorts of visualisations is in...
# Create a list of queries queries = [ 'telegraph', 'radio', 'wireless' ]
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now we'll define a new function that loops through each of the search terms, retrieving the facet data for each, and combining it all into a single dataframe.
def get_search_facets(params, queries): ''' Process a list of search queries, gathering the facet data for each and combining the results into a single dataframe. Parameters: params - basic parameters to send to the API queries - a list of search queries Returns: A dataframe...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Now we're ready to harvest some data!
df_queries = get_search_facets(params, queries)
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Once again, it would be useful to have the number of search results as a proportion of the total articles, so let's use our merge function again to add the proportions.
df_queries_merged = merge_df_with_total(df_queries, df_total)
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
As we're repeating the same sorts of charts with different data, we might as well save ourselves some effort by creating a couple of reusable charting functions. One shows the raw numbers, and the other shows the proportions.
def make_chart_totals(df, category, category_title): ''' Make a chart showing the raw number of search results over time. Creates different coloured lines for each query or category. Parameters: df - a dataframe category - the column containing the value that distinguishes multiple resul...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Let's use the new functions to create charts for our queries.
# Chart total results chart3 = make_chart_totals(df_queries_merged, 'query', 'Search query') # Chart proportions chart4 = make_chart_proportions(df_queries_merged, 'query', 'Search query') # Shorthand way of concatenating the two charts (note there's only one legend) chart3 & chart4
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Once again, it's interesting to compare the total results with the proportions. In this case, both point to something interesting happening around 1930. To explore this further we could use the [Trove Newspaper Harvester](https://glam-workbench.github.io/trove-harvester/) to assemble a dataset of articles from 1920 to ...
# A list of state values that we'll supply to the state facet states = [ 'New South Wales', 'Victoria' ]
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
...and our search query.
# Remember this time we're comparing a single search query across multiple states query = 'Chinese'
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
As before, we'll display both the raw number of results, and the proportion this represents of the total number of articles. But what is the total number of articles in this case? While we could generate a proportion using the totals for each year across all of Trove's newspapers, it seems more useful to use the total ...
def get_state_totals(state): ''' Get the total number of articles for each year for the specified state. Parameters: state Returns: A list of dictionaries containing 'year', 'total_results'. ''' these_params = params.copy() # Set the q parameter to a single space to get...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Let's get the data!
df_states = get_state_facets(params, states, query)
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
And now chart the results, specifying `state` as the column to use for our category.
# Chart totals chart5 = make_chart_totals(df_states, 'state', 'State') # Chart proportions chart6 = make_chart_proportions(df_states, 'state', 'State') # Shorthand way of concatenating the two charts (note there's only one legend) chart5 & chart6
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Showing the results as a proportion of the total articles for each state does seem to show up some interesting differences. Did 10% of newspaper articles published in Victoria in 1857 really mention 'Chinese'? That seems like something to investigate in more detail.Another way of visualising the number of results per s...
# Create a list of dictionaries, each with the 'id' and 'name' of a newspaper newspapers = [ {'id': 1180, 'name': 'Sydney Sun'}, {'id': 35, 'name': 'Sydney Morning Herald'}, {'id': 1002, 'name': 'Tribune'} ] # Our search query we want to compare across newspapers query = 'worker'
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
In this case the total number of articles we want to use in calculating the proportion of results is probably the total number of articles published in each particular newspaper. This should allow a more meaningful comparison between, for example, a weekly and a daily newspaper. As in the example above, we'll define a ...
def get_newspaper_totals(newspaper_id): ''' Get the total number of articles for each year for the specified newspaper. Parameters: newspaper_id - numeric Trove newspaper identifier Returns: A list of dictionaries containing 'year', 'total_results'. ''' these_params = params.copy...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Let's get the data!
df_newspapers = get_newspaper_facets(params, newspapers, query)
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
And make some charts!
# Chart totals chart7 = make_chart_totals(df_newspapers, 'newspaper', 'Newspaper') # Chart proportions chart8 = make_chart_proportions(df_newspapers, 'newspaper', 'Newspaper') # Shorthand way of concatenating the two charts (note there's only one legend) chart7 & chart8
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
8. Chart changes in illustration types over timeLet's try something a bit different and explore the *format* of articles rather than their text content. Trove includes a couple of facets that enable you to filter your search by type of illustration. First of all you have to set the `illustrated` facet to `true`, then ...
ill_types = [ 'Photo', 'Cartoon', 'Illustration', 'Map', 'Graph' ]
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers
Then we'll define a function to loop through the illustration types getting the year by year results of each.
def get_ill_facets(params, ill_types): ''' Loop through the supplied list of illustration types getting the year by year results. Parameters: params - basic parameters to send to the API ill_types - a list of illustration types to use with the ill_type facet Returns: A dataframe ...
_____no_output_____
MIT
visualise-searches-over-time.ipynb
GLAM-Workbench/trove-newspapers