markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Plot the PM2.5 Concentration, a measure of particulate air polution. | %matplotlib inline
sql="""
SELECT county_name, mrfei, pm25_concentration, percent as percent_poverty, geometry FROM geo as counties
LEFT JOIN hf_total ON hf_total.gvid = counties.gvid
LEFT JOIN aq_total ON aq_total.gvid = counties.gvid
LEFT JOIN pr_total ON pr_total.gvid = counties.gvid;
"""
w.geoframe(sql).plot(colum... | test/bundle_tests/build.example.com/classification/Using SQL JOINS.ipynb | CivicKnowledge/ambry | bsd-2-clause |
Create Dotstar object
You can pass several arguments to the Dotstar class constructor to change the behavior of the LED class.
ds = dotstar.Dotstar(led_count=72, bus=0, init_data=0, init_brightness=0)
Parameters:
led_count = some_number_of_leds
Change the number of LEDs in your strip. Note that this counts the raw nu... | ds = dotstar.Dotstar(led_count=72*3,init_brightness=0) | Dotstar-LED.ipynb | MinnowBoard/fishbowl-notebooks | mit |
Class Methods
Now we can make use of the functions in the class to set the colors and intesnity of each LED. The class works by populating a deque with the LED values you want, and then pushing all the data at once to the LED strip. The following methods provide the most basic functionality:
Dotstar.set(which_LED, bri... | while True:
for current_led in range (4, ds.led_count-4):
ds.set(current_led-4, 0, 0, 0, 0)
ds.set(current_led-2, 10, 100, 0, 0)
ds.set(current_led-1, 50, 200, 0, 0)
ds.set(current_led, 50, 250, 0, 0)
ds.set(current_led+1, 50, 200, 0, 0)
ds.set(current_led+2, 50, 150,... | Dotstar-LED.ipynb | MinnowBoard/fishbowl-notebooks | mit |
Next-word prediction task
Part 1: Data preparation
1.1. Loading data
Load and split the text of our story | def load_data(filename):
with open(filename) as f:
data = f.readlines()
data = [x.strip().lower() for x in data]
data = [data[i].split() for i in range(len(data))]
data = np.array(data)
data = np.reshape(data, [-1, ])
print(data)
return data
#Run the cell
train_file ='data/story.tx... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
1.2.Symbols encoding
The LSTM input's can only be numbers. A way to convert words (symbols or any items) to numbers is to assign a unique integer to each word. This process is often based on frequency of occurrence for efficient coding purpose.
Here, we define a function to build an indexed word dictionary (word->numbe... | def build_vocabulary(words):
count = collections.Counter(words).most_common()
dic= dict()
for word, _ in count:
dic[word] = len(dic)
reverse_dic= dict(zip(dic.values(), dic.keys()))
return dic, reverse_dic | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Run the cell below to display the vocabulary | dictionary, reverse_dictionary = build_vocabulary(train_data)
vocabulary_size= len(dictionary)
print "Dictionary size (Vocabulary size) = ", vocabulary_size
print("\n")
print("Dictionary : \n")
print(dictionary)
print("\n")
print("Reverted Dictionary : \n" )
print(reverse_dictionary) | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Part 2 : LSTM Model in TensorFlow
Since you have defined how the data will be modeled, you are now to develop an LSTM model to predict the word of following a sequence of 3 words.
2.1. Model definition
Define a 2-layers LSTM model.
For this use the following classes from the tensorflow.contrib library:
rnn.BasicLST... | def lstm_model(x, w, b, n_input, n_hidden):
# reshape to [1, n_input]
x = tf.reshape(x, [-1, n_input])
# Generate a n_input-element sequence of inputs
# (eg. [had] [a] [general] -> [20] [6] [33])
x = tf.split(x,n_input,1)
# 1-layer LSTM with n_hidden units.
rnn_cell = rnn.BasicLSTMCell(n_h... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Training Parameters and constants | # Training Parameters
learning_rate = 0.001
epochs = 50000
display_step = 1000
n_input = 3
#For each LSTM cell that you initialise, supply a value for the hidden dimension, number of units in LSTM cell
n_hidden = 64
# tf Graph input
x = tf.placeholder("float", [None, n_input, 1])
y = tf.placeholder("float", [None, vo... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Define the Loss/Cost and optimizer | # Loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
#cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
#cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(tf.clip_by_value(pred,-1.0,1.0)), reduction_indices=1))
optimizer = tf.train.RMSPropOptimi... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
We decided to apply the softmax and calculate the cost at the same time. In this way we can use the method softmax_cross_entropy_with_logits, which is more numerically stable in corner cases than applying the softmax and then calculating the cross entropy
We give you here the Test Function | #run the cell
def test(sentence, session, verbose=False):
sentence = sentence.strip()
words = sentence.split(' ')
if len(words) != n_input:
print("sentence length should be equel to", n_input, "!")
try:
symbols_inputs = [dictionary[str(words[i - n_input])] for i in range(n_input)]
... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Part 3 : LSTM Training
In the Training process, at each epoch, 3 words are taken from the training data, encoded to integer to form the input vector. The training labels are one-hot vector encoding the word that comes after the 3 inputs words. Display the loss and the training accuracy every 1000 iteration. Save the mo... | # Initializing the variables
init = tf.global_variables_initializer()
saver = tf.train.Saver()
start_time = time()
# Launch the graph
with tf.Session() as session:
session.run(init)
step = 0
offset = random.randint(0,n_input+1)
end_offset = n_input + 1
acc_total = 0
loss_total = 0
writer.ad... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
We created different models with different number of layers, and we have seen that the best accuracy is achieved using only 2 laers. Using more or less layers we achieve a lower accuracy
Part 4 : Test your model
3.1. Next word prediction
Load your model (using the model_saved variable given in the training ses... | with tf.Session() as sess:
# Initialize variables
sess.run(init)
# Restore model weights from previously saved model
saver.restore(sess, "./model.ckpt")
print(test('get a little', sess))
print(test('nobody tried to', sess)) | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
Here it looks that the RNN is working, in fact it can predict correctly the next word.
We should not that in this case is difficult to check if the RNN is actually overfitting the training data.
3.2. More fun with the Fable Writer !
You will use the RNN/LSTM model learned in the previous question to create a
... | #Your implementation goes here
with tf.Session() as sess:
# Initialize variables
sess.run(init)
# Restore model weights from previously saved model
saver.restore(sess, "./model.ckpt")
#a sentence is concluded when we find a dot.
fable = [random.choice(dictionary.keys()) for _ in range(3)]... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
This is interesting, we see that the sentences have some sort of sense, but when we reach a point, we see the same sentence repated many times. Thus is probably due to overfitting, we should look more deeply. We see that the repeated sentence is different from the original one, but it is still always the same.... | def load_data(filename):
with open(filename) as f:
data = f.readlines()
data = [x.strip().lower() for x in data]
data = [data[i].split() for i in range(len(data))]
data = np.array(data)
data = np.reshape(data, [-1, ])
return data
train_file ='data/story.txt'
train_data = load_data(train... | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
3.3. Play with number of inputs
The number of input in our example is 3, see what happens when you use other number (1 and 5)
n_input = 1 | create_train_model(n_input = 1, n_layers = 1)
create_train_model(n_input = 1, n_layers = 2)
create_train_model(n_input = 1, n_layers = 3) | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
Here we see that when the input size is 1 we obtain a vad model regardless of the number of layers, this is because we are basically predicting a word based on the preceding word. This not enough to create a sentence with some sort of sense.Looking ath the prediction accuracy, it is very low.
n_input = 3 | create_train_model(n_input = 3, n_layers = 1)
create_train_model(n_input = 3, n_layers = 2)
create_train_model(n_input = 3, n_layers = 3) | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Comment:
Here we see some sentences that have a sense, but we see a tendency to repeat the sentence of the training fable. This is interesting, because during the training the single triples where chosen randomly and not sequentially. Somehow, the net learned the training fable.
n_input = 5 | create_train_model(n_input = 5, n_layers = 1)
create_train_model(n_input = 5, n_layers = 2)
create_train_model(n_input = 5, n_layers = 3) | word_prediction_lstm/TP3-notebook.ipynb | fablln/Deep-Learning | mit |
Measures of central tendency identify values that lie on the center of a sample and help statisticians summarize their data. The most measures of central tendency are mean, median, and mode. Although you should be familiar with these values, they are defined as:
MEAN = sum(sample) / len(sample)
MEDIAN = sorted(sample)... | mean_cpm1 = sum(cpm)/len(cpm)
print('mean CPM from its definition is: %s' %mean_cpm1)
mean_cpm2 = np.mean(cpm)
print('mean CPM from built-in function is: %s' %mean_cpm2)
if len(cpm)%2 == 0:
median_cpm1 = sorted(cpm)[int(len(cpm)/2)]
else:
median_cpm1 = (sorted(cpm)[int((len(cpm)+1)/2)]+sorted(cpm)[int((len(c... | Programming Lesson Modules/Module 8- Measures of Central Tendency.ipynb | bearing/dosenet-analysis | mit |
Define An Address
The following address is of a Walgreens for an example. | address = RefuseQueryAddress(
house_number=2727,
direction='S',
street_name='27th',
street_type='st') | notebooks/SimpleQuery.ipynb | tomislacker/python-mke-trash-pickup | unlicense |
Execute The Query
Call the RefuseQuery class to fetch, parse, and return the status of
future refuse pickups. | pickup = RefuseQuery.Execute(address) | notebooks/SimpleQuery.ipynb | tomislacker/python-mke-trash-pickup | unlicense |
Assess Results
Look at the response object to determine what route the address is
on, when the next garbage pickup is, and when the next recycle pickup
will likely be. | print(repr(pickup)) | notebooks/SimpleQuery.ipynb | tomislacker/python-mke-trash-pickup | unlicense |
Example 1: interactplot | # Generate a random dataset with strong simple effects and an interaction
n = 80
rs = np.random.RandomState(11)
x1 = rs.randn(n)
x2 = x1 / 5 + rs.randn(n)
b0, b1, b2, b3 = .5, .25, -1, 2
y = b0 + b1 * x1 + b2 * x2 + b3 * x1 * x2 + rs.randn(n)
df = pd.DataFrame(np.c_[x1, x2, y], columns=["x1", "x2", "y"])
# Show a sca... | vmfiles/IPNB/Examples/b Graphics/30 Seaborn.ipynb | studentofdata/qcew | bsd-3-clause |
Example 2: Correlation matrix heatmap | sns.set(context="paper", font="monospace")
# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()
# Set up the matplotlib figure
f, ax = plt.subplots( figsize=(12, 9) )
# Draw the heatmap using seaborn
sns.heatmap(c... | vmfiles/IPNB/Examples/b Graphics/30 Seaborn.ipynb | studentofdata/qcew | bsd-3-clause |
Example 3: Linear regression with marginal distributions | sns.set(style="darkgrid", color_codes=True)
tips = sns.load_dataset("tips")
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
xlim=(0, 60), ylim=(0, 12), color="r", size=7)
| vmfiles/IPNB/Examples/b Graphics/30 Seaborn.ipynb | studentofdata/qcew | bsd-3-clause |
Interactivity
We repeat the above example, but now using mpld3 to provide pan & zoom interactivity.
Note that this may not work if graphics have already been initialized | # Seaborn + interactivity through mpld3
import mpld3
sns.set( style="darkgrid", color_codes=True )
tips = sns.load_dataset("tips")
sns.jointplot( "total_bill", "tip", data=tips, kind="reg",
xlim=(0, 60), ylim=(0, 12), color="r", size=7 )
mpld3.display() | vmfiles/IPNB/Examples/b Graphics/30 Seaborn.ipynb | studentofdata/qcew | bsd-3-clause |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
used min-max normalization
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
max_value = 255
min_value = 0
return (x - min_value) / (max_value - ... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | from sklearn import preprocessing
lb=preprocessing.LabelBinarizer()
lb.fit(range(10))
def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
return lb.trans... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
def neural_net_image_input(image_shape):
"""
Return a Tensor for a bach of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
shape = [x for x in image_shape]
shape.insert(0, None)
return tf.placeholder(tf.float32, shape=shape, n... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal size 2-D Tuple fo... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag... | def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_out... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Act... | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
conv_output_depth = {
'layer1': 32,
'laye... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. | def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy... | image-classification/dlnd_image_classification.ipynb | postBG/DL_project | mit |
Generate a circuit that computes this function. To implement the logical operations we use standard verilog gates, which are available in mantle.verilog.gates. | import magma as m
import mantle
class VerilatorExample(m.Circuit):
io = m.IO(a=m.In(m.Bit), b=m.In(m.Bit), c=m.In(m.Bit), d=m.Out(m.Bit))
io.d <= f(io.a, io.b, io.c)
m.compile("build/VerilatorExample", VerilatorExample, "coreir-verilog", inline=True)
%cat build/VerilatorExample.v | notebooks/advanced/verilator.ipynb | phanrahan/magmathon | mit |
Next, generate a verilator test harness in C++ for the circuit. The test vectors are generated using the python function f. The verilator test bench compares the output of the simulator to those test vectors. | from itertools import product
from fault import Tester
tester = Tester(VerilatorExample)
for a, b, c in product([0, 1], [0, 1], [0, 1]):
tester.poke(VerilatorExample.a, a)
tester.poke(VerilatorExample.b, b)
tester.poke(VerilatorExample.c, c)
tester.eval()
tester.expect(VerilatorExample.d, f(a, b, c... | notebooks/advanced/verilator.ipynb | phanrahan/magmathon | mit |
Using fault, we can use the same tester and (with the same testbench inputs/expectations) and use a different backend, like the python simulator. | tester.compile_and_run("python") | notebooks/advanced/verilator.ipynb | phanrahan/magmathon | mit |
1. Input Parameters
The inputs that need to be provided to activate the radioactive option are:
the list of selected radioactive isotopes,
the radioactive yield tables.
The list of isotopes is declared in the yield_tables/decay_info.txt file and can be modified prior any simulation. The radioactive yields are found ... | # Number of timesteps in the simulaton.
# See https://github.com/NuGrid/NuPyCEE/blob/master/DOC/Capabilities/Timesteps_size_management.ipynb
special_timesteps = -1
nb_dt = 100
tend = 2.0e6
dt = tend / float(nb_dt)
# No star formation.
no_sf = True
# Dummy neutron star merger yields to activate the radioactive option.... | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Run SYGMA | # Run SYGMA (or in this case, the decay process)
s = sygma.sygma(iniZ=0.02, no_sf=no_sf, ism_ini_radio=ism_ini_radio,\
special_timesteps=special_timesteps, tend=tend, dt=dt,\
decay_file='yield_tables/decay_file.txt', nsmerger_table_radio=nsmerger_table_radio)
# Get the Al-26 (radioactiv... | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Plot results | # Plot the evolution of Al-26 and Mg-26
%matplotlib nbagg
plt.figure(figsize=(8,4.5))
plt.plot( np.array(s.history.age)/1e6, Al_26, '--b', label='Al-26' )
plt.plot( np.array(s.history.age)/1e6, Mg_26, '-r', label='Mg-26' )
plt.plot([0,2.0], [0.5,0.5], ':k')
plt.plot([0.717,0.717], [0,1], ':k')
# Labels and fontsizes
... | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
3. Multiple Decay Channels
If the radioactive isotopes you selected have more than one decay channel, you need to use the provided decay module. This option can be activated by adding use_decay_module=True in the list of parameters when creating an instance of SYGMA and OMEGA. When using the decay module, the yield_t... | # Add 1 Msun of radioactive K-40 in the gas.
# The indexes of this array reflect the order seen in the yield_tables/decay_file.txt file
# Index 0, 1, 2 --> Al-26, K-40, U-238
ism_ini_radio = [0.0, 1.0, 0.0]
# Number of timesteps in the simulaton.
# See https://github.com/NuGrid/NuPyCEE/blob/master/DOC/Capabilities/Tim... | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Example with U-238 | # Add 1 Msun of radioactive U-238 in the gas.
# The indexes of this array reflect the order seen in the yield_tables/decay_file.txt file
# Index 0, 1, 2 --> Al-26, K-40, U-238
ism_ini_radio = [0.0, 0.0, 1.0]
# Number of timesteps in the simulaton.
# See https://github.com/NuGrid/NuPyCEE/blob/master/DOC/Capabilities/Ti... | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
In the case of U-238, there are many isotopes that are resulting from the multiple decay channels. Those new radioactive isotopes are added automatically in the list of isotopes in NuPyCEE. | print(s.radio_iso) | DOC/Capabilities/Including_radioactive_isotopes.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Basics of MapReduce | from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/gI4HN0JhPmo" frameborder="0" allowfullscreen></iframe>') | 1-uIDS-courseNotes/l5-MapReduce.ipynb | tanle8/Data-Science | mit |
Quiz: Couting Words Serially
```Python
import logging
import sys
import string
from util import logfile
logging.basicConfig(filename=logfile, format='%(message)s',
level=logging.INFO, filemode='w')
def word_count():
# For this exercise, write a program that serially counts the number of occurrenc... | from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/onseMon9zqA" frameborder="0" allowfullscreen></iframe>')
from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/_q6098sNqpo" frameborder="0" allowfullscreen>... | 1-uIDS-courseNotes/l5-MapReduce.ipynb | tanle8/Data-Science | mit |
Mapper | from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/mPYxFC7DI28" frameborder="0" allowfullscreen></iframe>') | 1-uIDS-courseNotes/l5-MapReduce.ipynb | tanle8/Data-Science | mit |
Reducer | from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/bkhuEG0D2HM" frameborder="0" allowfullscreen></iframe>') | 1-uIDS-courseNotes/l5-MapReduce.ipynb | tanle8/Data-Science | mit |
Quiz: Mapper And Reducer With Aadhaar Data
aadhaar_genereated_mapper.py
```Python
import sys
import string
import logging
from util import mapper_logfile
logging.basicConfig(filename=mapper_logfile, format='%(message)s',
level=logging.INFO, filemode='w')
def mapper():
#Also make sure to fill out the... | # Recap
from IPython.display import HTML
HTML('<iframe width="798" height="449" src="https://www.youtube.com/embed/Pl68U2iGtyI" frameborder="0" allowfullscreen></iframe>') | 1-uIDS-courseNotes/l5-MapReduce.ipynb | tanle8/Data-Science | mit |
Expected Output:
<table>
<tr>
<td > **W1** </td>
<td > [[ 1.63535156 -0.62320365 -0.53718766]
[-1.07799357 0.85639907 -2.29470142]] </td>
</tr>
<tr>
<td > **b1** </td>
<td > [[ 1.74604067]
[-0.75184921]] </td>
</tr>
<tr>
<td > **W2** </td>
<t... | # GRADED FUNCTION: random_mini_batches
def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples)
Y -- true "label" vector (1 for blue dot / 0 for red dot), of shape (... | deep-learnining-specialization/2. improving deep neural networks/week2/Optimization methods.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table style="width:40%">
<tr>
<td > **v["dW1"]** </td>
<td > [[ 0. 0. 0.]
[ 0. 0. 0.]] </td>
</tr>
<tr>
<td > **v["db1"]** </td>
<td > [[ 0.]
[ 0.]] </td>
</tr>
<tr>
<td > **v["dW2"]** </td>
<td > [[ 0. 0. 0.]
[ 0. 0.... | # GRADED FUNCTION: update_parameters_with_adam
def update_parameters_with_adam(parameters, grads, v, s, t, learning_rate = 0.01,
beta1 = 0.9, beta2 = 0.999, epsilon = 1e-8):
"""
Update parameters using Adam
Arguments:
parameters -- python dictionary containing your... | deep-learnining-specialization/2. improving deep neural networks/week2/Optimization methods.ipynb | diegocavalca/Studies | cc0-1.0 |
Filter for stoichiometric compounds only: | def is_stoichiometric(composition):
return np.all(np.mod(composition.values(), 1) == 0)
stoichiometric_compositions = [c for c in compositions if is_stoichiometric(c)]
print("Number of stoichiometric compositions: {}".format(len(stoichiometric_compositions)))
ternaries = set(c.formula for c in stoichiometric_compo... | notebooks/old_ICSD_Notebooks/Understanding ICSD data.ipynb | 3juholee/materialproject_ml | mit |
3. Calculate the basic descriptive statistics on the data | df.mean()
df.median()
#range
df["Exposure"].max() - df["Exposure"].min()
#range
df["Mortality"].max() - df["Mortality"].min()
df.std()
df.corr() | class7/donow/benzaquen_mercy_donow_7.ipynb | ledeprogram/algorithms | gpl-3.0 |
4. Find a reasonable threshold to say exposure is high and recode the data | #IQR
IQR= df['Exposure'].quantile(q=0.75)- df['Exposure'].quantile(q=0.25) | class7/donow/benzaquen_mercy_donow_7.ipynb | ledeprogram/algorithms | gpl-3.0 |
UAL= (IQR * 1.5) +Q3
LAL= Q1- (IQR * 1.5)
Anything outside of UAL and LAL is an outlier | Q1= df['Exposure'].quantile(q=0.25) #1st Quartile
Q1
Q2= df['Exposure'].quantile(q=0.5) #2nd Quartile (Median)
Q3= df['Exposure'].quantile(q=0.75) #3rd Quartile
UAL= (IQR * 1.5) +Q3
UAL
LAL= Q1- (IQR * 1.5)
LAL | class7/donow/benzaquen_mercy_donow_7.ipynb | ledeprogram/algorithms | gpl-3.0 |
This notebook reviews some of the Python modules that make it possible to work with data structures in an easy an efficient manner. We will review Numpy arrays and matrices, and some of the common operations which are needed when working with these data structures in Machine Learning.
1. Create numpy arrays of differen... | x = [5, 4, 3, 4]
print(type(x[0]))
# Create a list of floats containing the same elements as in x
# x_f = list(map(<FILL IN>))
x_f = list(map(float, x))
test_arrayequal(x, x_f, 'Elements of both lists are not the same')
if ((type(x[-2])==int) & (type(x_f[-2])==float)):
print('Test passed')
else:
print('Type... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
Numpy arrays can be defined directly using methods such as np.arange(), np.ones(), np.zeros(), as well as random number generators. Alternatively, you can easily generate them from python lists (or lists of lists) containing elements of numeric type.
You can easily check the shape of any numpy vector with the property ... | # Numpy arrays can be created from numeric lists or using different numpy methods
y = np.arange(8)+1
x = np.array(x_f)
# Check the different data types involved
print('Variable x_f is of type', type(x_f))
print('Variable x is of type ', type(x))
print('Variable y is of type', type(y))
# Print the shapes of the numpy ... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
2. Products and powers of numpy arrays and matrices
* and ** when used with Numpy arrays implement elementwise product and exponentiation
* and ** when used with Numpy matrices implement matrix product and exponentiation
Method np.dot() implements matrix multiplication, and can be used both with numpy arrays and matri... | # Try to run the following command on variable x_matrix, and check what happens
print(x_array**2)
print('Remember that the shape of x_array is', x_array.shape)
print('Remember that the shape of y is', y.shape)
# Complete the following exercises. You can print the partial results to visualize them
# Multiply the 2-D ... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
Other numpy methods where you can specify the axis along with a certain operation should be carried out are:
np.median()
np.std()
np.var()
np.percentile()
np.sort()
np.argsort()
If the axis argument is not provided, the array is flattened before carriying out the corresponding operation.
4. Concatenating matrices and... | # Previous check that you are working with the right matrices
test_hashedequal(z_4_2.tostring(),'0727ed01af0aa4175316d3916fd1c8fe2eb98f27','Incorrect result for variable z_4_2')
test_hashedequal(x_array.tostring(), '1215ced5d82501bf03e04b30f16c45a4bdcb8838', 'Incorrect variable x_array')
# Vertically stack matrix z_4_... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
5. Slicing
Particular elements of numpy arrays (both unidimensional and multidimensional) can be accessed using standard python slicing. When working with multidimensional arrays, slicing can be carried out along the different dimensions at once | # Keep last row of matrix X
# X_sub1 = <FILL IN>
X_sub1 = X[-1,]
# Keep first column of the three first rows of X
# X_sub2 = <FILL IN>
X_sub2 = X[:3,0]
# Keep first two columns of the three first rows of X
# X_sub3 = <FILL IN>
X_sub3 = X[:3,:2]
# Invert the order of the rows of X
# X_sub4 = <FILL IN>
X_sub4 = X[::-1... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
7.1. Non-linear transformations
Create a new matrix Z, where additional features are created by carrying out the following non-linear transformations:
$${\bf Z} = \left[ \begin{array}{ccc} 1 & x_1^{(1)} & x_2^{(1)} & \log\left(x_1^{(1)}\right) & \log\left(x_2^{(1)}\right)\ 1 & x_1^{(2)} & x_2^{(2)} & \log\left(x_1^{(2)... | # Obtain matrix Z using concatenation functions
# Z = np.hstack(<FILL IN>)
Z = np.hstack((X,np.log(X[:,1:])))
test_hashedequal(Z.tostring(),'737dee4c168c5ce8fc53a5ec5cad43b5a53c7656','Incorrect matrix Z') | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
Repeat the previous exercise, this time using the map() method together with function log_transform(). This function needs to be defined in such a way that guarantees that variable Z_map is the same as the previously computed variable Z. | def log_transform(x):
# return <FILL IN>
return np.hstack((x,np.log(x[1]),np.log(x[2])))
Z_map = np.array(list(map(log_transform,X)))
test_hashedequal(Z_map.tostring(),'737dee4c168c5ce8fc53a5ec5cad43b5a53c7656','Incorrect matrix Z') | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
Repeat the previous exercise once more. This time, define a lambda function for the task. | # Z_lambda = np.array(list(map(lambda x: <FILL IN>,X)))
Z_lambda = np.array(list(map(lambda x: np.hstack((x,np.log(x[1]),np.log(x[2]))),X)))
test_hashedequal(Z_lambda.tostring(),'737dee4c168c5ce8fc53a5ec5cad43b5a53c7656','Incorrect matrix Z') | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
7.2. Polynomial transformations
Similarly to the previous exercise, now we are interested in obtaining another matrix that will be used to evaluate a polynomial model. In order to do so, compute matrix Z_poly as follows:
$$Z_\text{poly} = \left[ \begin{array}{cccc} 1 & x_1^{(1)} & (x_1^{(1)})^2 & (x_1^{(1)})^3 \ 1 & x_... | # Calculate variable Z_poly, using any method that you want
# Z_poly = <FILL IN>
Z_poly = np.array(list(map(lambda x: np.array([x[1]**k for k in range(4)]),X)))
test_hashedequal(Z_poly.tostring(),'7e025512fcee1c1db317a1a30f01a0d4b5e46e67','Wrong variable Z_poly') | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
7.3. Model evaluation
Finally, we can use previous data matrices Z and Z_poly to efficiently compute the output of the corresponding non-linear models over all the patterns in the data set. In this exercise, we consider the two following linear-in-the-parameters models to be evaluated:
$$f_\text{log}({\bf x}) = w_0 + w... | w_log = np.array([3.3, 0.5, -2.4, 3.7, -2.9])
w_poly = np.array([3.2, 4.5, -3.2, 0.7])
# f_log = <FILL IN>
f_log = Z.dot(w_log)
# f_poly = <FILL IN>
f_poly = Z_poly.dot(w_poly)
test_hashedequal(f_log.tostring(),'d5801dfbd603f6db7010b9ef80fa48e351c0b38b','Incorrect evaluation of the logarithmic model')
test_hashedeq... | P2.Numpy/old/numpy_professor.ipynb | ML4DS/ML4all | mit |
<p>Agora vamos ler os dois corpus e armazenar as sentenças em uma mesma ndarray. Perceba que também teremos uma ndarray para indicar se o texto é formal ou não. Começamos armazenando o corpus em lists. Vamos usar apenas 500 elementos de cada, para fins didáticos.</p> | import nltk
x_data_nps = []
for fileid in nltk.corpus.nps_chat.fileids():
x_data_nps.extend([post.text for post in nps_chat.xml_posts(fileid)])
y_data_nps = [0] * len(x_data_nps)
x_data_gut = []
for fileid in nltk.corpus.gutenberg.fileids():
x_data_gut.extend([' '.join(sent) for sent in nltk.corpus.gutenber... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<p>Em seguida, transformamos essas listas em ndarrays, para usarmos nas etapas de pré-processamento que já conhecemos.</p> | import numpy as np
x_data = np.array(x_data_full, dtype=object)
#x_data = np.array(x_data_full)
print(x_data.shape)
y_data = np.array(y_data_full)
print(y_data.shape) | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<b>2. Dividindo em datasets de treino e teste</b>
<p>Para que a pesquisa seja confiável, precisamos avaliar os resultados em um dataset de teste. Por isso, vamos dividir os dados aleatoriamente, deixando 80% para treino e o demais para testar os resultados em breve.</p> | train_indexes = np.random.rand(len(x_data)) < 0.80
print(len(train_indexes))
print(train_indexes[:10])
x_data_train = x_data[train_indexes]
y_data_train = y_data[train_indexes]
print(len(x_data_train))
print(len(y_data_train))
x_data_test = x_data[~train_indexes]
y_data_test = y_data[~train_indexes]
print(len(x_da... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<b>3. Treinando o classificador</b>
<p>Para tokenização, vamos usar a mesma função do tutorial anterior:</p> | from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
import string
from nltk.corpus import wordnet
stopwords_list = stopwords.words('english')
lemmatizer = WordNetLemmatizer()
def my_tokenizer(doc):
words = word_tokenize(doc)
... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<p>Mas agora vamos criar um <b>pipeline</b> contendo o vetorizador TF-IDF, o SVD para redução de atributos e um algoritmo de classificação. Mas antes, vamos encapsular nosso algoritmo para escolher o número de dimensões para o SVD em uma classe que pode ser utilizada com o pipeline:</p> | from sklearn.decomposition import TruncatedSVD
class SVDDimSelect(object):
def fit(self, X, y=None):
self.svd_transformer = TruncatedSVD(n_components=X.shape[1]/2)
self.svd_transformer.fit(X)
cummulative_variance = 0.0
k = 0
for var in sorted(self.svd... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<p>Finalmente podemos criar nosso pipeline:</p> | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.pipeline import Pipeline
from sklearn import neighbors
clf = neighbors.KNeighborsClassifier(n_neighbors=10, weights='uniform')
my_pipeline = Pipeline([('tfidf', TfidfVectorizer(tokenizer=my_tokenizer)),\
('svd', SVDDimSele... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<p>Estamos quase lá... Agora vamos criar um objeto <b>RandomizedSearchCV</b> que fará a seleção de hiper-parâmetros do nosso classificador (aka. parâmetros que não são aprendidos durante o treinamento). Essa etapa é importante para obtermos a melhor configuração do algoritmo de classificação. Para economizar tempo de t... | from sklearn.grid_search import RandomizedSearchCV
import scipy
par = {'clf__n_neighbors': range(1, 60), 'clf__weights': ['uniform', 'distance']}
hyperpar_selector = RandomizedSearchCV(my_pipeline, par, cv=3, scoring='accuracy', n_jobs=2, n_iter=20)
| nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<p>E agora vamos treinar nosso algoritmo, usando o pipeline com seleção de atributos:</p> | #print(hyperpar_selector)
hyperpar_selector.fit(X=x_data_train, y=y_data_train)
print("Best score: %0.3f" % hyperpar_selector.best_score_)
print("Best parameters set:")
best_parameters = hyperpar_selector.best_estimator_.get_params()
for param_name in sorted(par.keys()):
print("\t%s: %r" % (param_name, best_param... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<b>4. Testando o classificador</b>
<p>Agora vamos usar o classificador com o nosso dataset de testes, e observar os resultados:</p> | from sklearn.metrics import *
y_pred = hyperpar_selector.predict(x_data_test)
print(accuracy_score(y_data_test, y_pred)) | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<b>5. Serializando o modelo</b><br> | import pickle
string_obj = pickle.dumps(hyperpar_selector)
model_file = open('model.pkl', 'wb')
model_file.write(string_obj)
model_file.close() | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
<b>6. Abrindo e usando um modelo salvo </b><br> |
model_file = open('model.pkl', 'rb')
model_content = model_file.read()
obj_classifier = pickle.loads(model_content)
model_file.close()
res = obj_classifier.predict(["what's up bro?"])
print(res)
res = obj_classifier.predict(x_data_test)
print(accuracy_score(y_data_test, res))
res = obj_classifier.predict(x_data_... | nlp_classification_pt-br.ipynb | fernandojvdasilva/nlp-python-lectures | gpl-3.0 |
Data frames | #import data and then display each data frame
path1 = 'data/fbi_table_20years.xlsx'
df_20yr = pd.read_excel(path1,
index_col=0)
path2 = 'data/fbi_table_20years_edited.xlsx'
df_20yr_real = pd.read_excel(path2,
index_col=0)
path3 = 'data/fbi_table_20years_rates.xlsx'
... | UG_F16/Kustas-Madej-CrimeRatesFinalProject.ipynb | NYUDataBootcamp/Projects | mit |
Line Chart: Crime rate (1994-2013) | #create a line plot from crime rates data frame
fig, ax = plt.subplots()
df_20yr_rates.plot(ax=ax,
kind='line', # line plot
title='Different Crimes vs. Time\n\n',
grid = True,
ylim = (-50,3100),
marker = 'o',
use_index = True)
plt.legend(loc = 'upper r... | UG_F16/Kustas-Madej-CrimeRatesFinalProject.ipynb | NYUDataBootcamp/Projects | mit |
Analysis:
In the above graph, we can observe a steady decline (despite a few isolated increases) in crime rates across different categories of crime from 1994 to 2013. A number of explanations have been proposed to explain the trend. Historian Neil Howe has suggested that decline might come from the entrance of millenn... | #find totals of each column in order to find which crime was most prevalent over the course of the past 20 years
murder_total = 0
rape_total = 0
robbery_total = 0
agg_ass_total = 0
burglary_total = 0
larceny_total = 0
veh_total = 0
totals_list = []
list_total = 0
#find total number of murders
for i in (df_20yr_real.... | UG_F16/Kustas-Madej-CrimeRatesFinalProject.ipynb | NYUDataBootcamp/Projects | mit |
Analysis:
Here we can see the relative prevalence of various types of crime in the United States. Larceny theft accounts for over 50% of the crime committed in the US over the relevant 20-year period followed by burglary and motor vehicle theft contributing about 19% and about 10%, respectively. Rape, murder, aggravate... | #calculate total number of crimes per year
row_total = 0
row_total_list = []
count = 0
for i in (df_20yr_real.index):
for x in (df_20yr_real.columns):
row_total += df_20yr_real[x][i]
row_total_list.append(row_total)
row_total = 0
#calculate percent change in crimes between each year and then add ... | UG_F16/Kustas-Madej-CrimeRatesFinalProject.ipynb | NYUDataBootcamp/Projects | mit |
Analysis:
We can see from the above bar chart that there was a substantial decrease in crime during the year 1997 and 1998, this could be attributed to a number of increasingly rigorous policing tactics around the country, Bratton’s Zero Tolerance policing in New York City for example.
In addition to stricter policing... | #create a line plot from CDC data frame
fig, ax = plt.subplots()
df_CDC.plot(ax=ax,
kind='line', # line plot
grid = True,
marker = 'o',
use_index = True)
plt.legend(loc = 'upper right') #format legend
ax.set_title('High schoolers partaking in risky behaviors',fo... | UG_F16/Kustas-Madej-CrimeRatesFinalProject.ipynb | NYUDataBootcamp/Projects | mit |
Useful functions | def logistic_lin( x, a, b ):
"""Calculates the standard linear logistic function (probability distribution)
for x (which can be a scalar or a numpy array).
"""
return 1.0 / (1.0 + np.exp(-(a + b*x)))
def logistic_polyn( x, params ):
"""Calculates the general polynomial form of the logistic fu... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Defining different subsamples via index vectors
Lists of integers defining indices of galaxies in Parent Disc Sample which meet various criteria
that define specific subsamples. | ii_barred = [i for i in range(nDisksTotal) if s4gdata.sma[i] > 0]
ii_unbarred = [i for i in range(nDisksTotal) if s4gdata.sma[i] <= 0]
ii_spirals = [i for i in range(nDisksTotal) if s4gdata.t_s4g[i] > -0.5]
ii_barred_spirals = [i for i in ii_spirals if i in ii_barred]
ii_unbarred_spirals = [i for i in ii_spirals if i ... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Generate files for logistic regression with R
This code will regenerate the input files for the logistic regression analysis in R (see R notebook s4gbars_R_logistic-regression.ipynb)
By default, this will save the file in the data/ subdirectory, overwriting the pre-existing files. To change the destination, redefine da... | # optionally redefine dataDir to save files in a different location
# dataDir = XXX
outf = open(dataDir+"barpresence_vs_logmstar_for_R.txt", 'w')
outf.write("# Bar presence as function of log(M_star/M_sun) for D < 25 Mpc\n")
outf.write("logmstar bar\n")
for i in ii_all_limited1:
logmstar = s4gdata.logmstar[i]
... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figures
Figure 1
Left panel: Distances of galaxies in S4G Parent Disk Sample vs stellar mass | plt.plot(s4gdata.dist, s4gdata.logmstar, 'ko', mfc='None', mec='k',ms=4)
plt.plot(s4gdata.dist[ii_barred], s4gdata.logmstar[ii_barred], 'ko',ms=3.5)
plt.axvline(25)
plt.axvline(30, ls='--')
plt.axhline(8.5)
plt.axhline(9, ls='--')
xlim(0,60)
plt.xlabel("Distance [Mpc]"); plt.ylabel(xtmstar)
if savePlots: plt.savefig(pl... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Right panel: $R_{25}$ vs distance for S4G spirals | # define extra subsample for plot: all spirals with log(M_star) >= 9
ii_logmstar9 = [i for i in ii_spirals if s4gdata.logmstar[i] >= 9]
plot(s4gdata.dist[ii_spirals], s4gdata.R25_kpc[ii_spirals], 'o', mfc='None', mec='0.25',ms=4)
plot(s4gdata.dist[ii_logmstar9], s4gdata.R25_kpc[ii_logmstar9], 'cD', mec='k', ms=4)
xlim... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure 2
Left panel: $g - r$ vs stellar mass | # define extra subsamples for plot: galaxies with valid B-V_tc values; subsets at different distances
ii_bmv_good = [i for i in range(nDisksTotal) if s4gdata.BmV_tc[i] > -2]
iii25 = [i for i in ii_bmv_good if s4gdata.dist[i] <= 25]
iii25to30 = [i for i in ii_bmv_good if s4gdata.dist[i] > 25 and s4gdata.dist[i] <= 30]
i... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Right panel: Gas mass ratio $f_{\rm gas}$ vs stellar mass | # define extra subsamples for plot: galaxies with valid H_I meassurements; subsets at different distances
iii25 = [i for i in ii_spirals if s4gdata.M_HI[i] < 1.0e40 and s4gdata.dist[i] <= 25]
iii25to30 = [i for i in ii_spirals if s4gdata.M_HI[i] < 1.0e40 and s4gdata.dist[i] > 25 and s4gdata.dist[i] <= 30]
iii_larger = ... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure 4: Histogram of stellar masses in different subsamples | hist(s4gdata.logmstar, bins=np.arange(7,12,0.5), color='1.0', label="All", edgecolor='k')
hist(s4gdata.logmstar[ii_all_limited2], bins=np.arange(7,12,0.5), color='0.9', edgecolor='k', label=r"$D < 30$ Mpc")
hist(s4gdata.logmstar[ii_all_limited1], bins=np.arange(7,12,0.5), color='g', edgecolor='k', label=r"$D < 25$ Mpc"... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure 5: Bar fraction as function of stellar mass, color, gas mass fraction
The code here is for the six individual panels of the figure
Upper left panel: Bar frequency vs stellar mass | # load Barazza+2008 bar frequencies
logmstar_b08,fbar_b08,fbar_e_low_b08,fbar_e_high_b08 = GetBarazzaData(fbarLitDir+"fbar-vs-logmstar_barazza+2008.txt")
# load other SDSS-based bar frequencies
logmstar_na10,fbar_na10 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-logMstar_nair-abraham2010.txt")
logmstar_m12,fbar_m... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Upper right panel: SB and SAB frequencies vs stellar mass | pu.PlotFrequencyWithWeights(s4gdata.logmstar, s4gdata.w25, ii_SB_limited1, ii_nonSB_limited1, 8.0, 11.3, 0.25, fmt='ko',ms=8, label=r'SB (S$^{4}$G: $D \leq 25$ Mpc)')
pu.PlotFrequencyWithWeights(s4gdata.logmstar, s4gdata.w25, ii_SAB_limited1, ii_nonSAB_limited1, 8.0, 11.3, 0.25, offset=0.03, fmt='co', mec='k', ms=8, no... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Middle left panel: Bar frequency vs color | gmr_b08,fbar_b08,fbar_e_low_b08,fbar_e_high_b08 = GetBarazzaData(fbarLitDir+"fbar-vs-gmr_barazza+2008.txt")
gmr_na10,fbar_na10 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-gmr_nair-abraham2010.txt")
gmr_m11,fbar_m11 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-gmr_masters+2011.txt")
gmr_m12,fbar_m12 = s4gutil... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Middle right panel: SB and SAB frequencies vs color | pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww25, ii_SB_limited1_m8_5, ii_nonSB_limited1_m8_5, -0.2,1,0.1, fmt='ko', ms=8, label="SB ("+ss1m+")")
pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww25, ii_SAB_limited1_m8_5, ii_nonSAB_limited1_m8_5, -0.2,1,0.1, fmt='co', mec='k', ms=8, noErase=True, label="SAB ("+ss1m+")")
pl... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Lower left panel: Bar frequency vs gas mass ratio | logfgas_m12,fbar_m12 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-logfgas_masters+2012.txt")
logfgas_cs17_raw,fbar_cs17 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-logfgas_cervantes_sodi2017.txt")
# correct CS17 values from log M_{HI + He}/M_{star} to log M_{HI}/M_{star}
logfgas_cs17 = logfgas_cs17_raw - 0.1... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Lower right panel: SB and SAB frequencies vs gas mass ratio | pu.PlotFrequencyWithWeights(s4gdata.logfgas, s4gdata.w25, ii_SB_limited1_m8_5, ii_nonSB_limited1_m8_5, -3,1.5,0.5, fmt='ko', ms=8, label="SB ("+ss1m+")")
pu.PlotFrequencyWithWeights(s4gdata.logfgas, s4gdata.w25, ii_SAB_limited1_m8_5, ii_nonSAB_limited1_m8_5, -3,1.5,0.5, fmt='co', mec='k', ms=8, noErase=True, label="SAB... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure A1
We generate an interpolating spline using an edited version of the actual binned f(B_tc) values -- basically, we ensure that the spline interpolation goes smoothly to 0 for faint magnitudes and smoothly to 1 for bright magnitudes. | # generate Akima spline interpolation for f(B-V) as function of B_tc
x_Btc = [7.0, 8.25, 8.75, 9.25, 9.75, 10.25, 10.75, 11.25, 11.75, 12.25, 12.75, 13.25, 13.75, 14.25, 14.75, 15.25, 15.75, 16.25]
y_fBmV = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.9722222222222222, 0.8840579710144928, 0.8125, 0.6222222222222222, 0.563218390804... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure A2
Left panel | pu.PlotFrequencyWithWeights(s4gdata.BmV_tc, s4gdata.weight_BmVtc, ii_barred_limited2_m9, ii_unbarred_limited2_m9, 0,1,0.1, fmt='ko', ms=9, label=ss2m);
pu.PlotFrequencyWithWeights(s4gdata.BmV_tc, s4gdata.weight_BmVtc, ii_barred_limited1_m8_5, ii_unbarred_limited1_m8_5, 0,1,0.1, offset=0.01, fmt='ro', ms=9, noErase=True... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Right panel | ww25 = s4gdata.weight_BmVtc * s4gdata.w25
ww30 = s4gdata.weight_BmVtc * s4gdata.w30
pu.PlotFrequencyWithWeights(s4gdata.BmV_tc, ww25, ii_SB_limited1_m8_5, ii_nonSB_limited1_m8_5, -0.2,1,0.1, fmt='ko', ms=8, label="SB ("+ss1+")")
pu.PlotFrequencyWithWeights(s4gdata.BmV_tc, ww30, ii_SAB_limited1_m8_5, ii_nonSAB_limited1... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Figure B1
Upper left panel | # load Diaz-Garcia+2016a fractions
logmstar_dg16,fbar_dg16 = s4gutils.Read2ColumnProfile(fbarLitDir+"fbar-vs-logMstar_diaz-garcia+2016a.txt")
pu.PlotFrequency(s4gdata.logmstar, ii_barred_limited1, ii_unbarred_limited1, 8.0, 11.3, 0.25, fmt='ro', ms=9, label=ss1)
pu.PlotFrequency(s4gdata.logmstar, ii_barred_limited2, i... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Upper right panel | pu.PlotFrequencyWithWeights(s4gdata.logmstar, s4gdata.w25, ii_SB_limited1, ii_nonSB_limited1, 8.0, 11.3, 0.25, fmt='ko', ms=8, label=r'SB (S$^{4}$G: $D \leq 25$ Mpc)')
pu.PlotFrequencyWithWeights(s4gdata.logmstar, s4gdata.w30, ii_SB_limited2, ii_nonSB_limited2, 8.0, 11.3, 0.25, noErase=True, ms=8, fmt='ko', mfc='None',... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Left middle panel | pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww25, ii_barred_limited1_m8_5, ii_unbarred_limited1_m8_5, -0.2,1.0,0.1, fmt='ro', ms=9, label=ss1m)
pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww30, ii_barred_limited2_m9, ii_unbarred_limited2_m9, -0.2,1.0,0.1, offset=0.01, fmt='ro', mfc='None', mew=1, mec='r', ms=8, noErase... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Right middle panel | pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww25, ii_SB_limited1_m8_5, ii_nonSB_limited1_m8_5, 0,1,0.1, fmt='ko', ms=8, label="SB ("+ss1m+")")
pu.PlotFrequencyWithWeights(s4gdata.gmr_tc, ww30, ii_SB_limited2_m9, ii_nonSB_limited2_m9, 0,1,0.1, noErase=True, ms=8, fmt='ko', mfc='None', offset=0.01, label="SB ("+ss2m+")")... | s4gbars_main.ipynb | perwin/s4g_barfractions | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.