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 |
|---|---|---|---|---|---|
Run the prediction process | predict(predict_config) | _____no_output_____ | Apache-2.0 | 3_Prediction.ipynb | dymaxionlabs/burned-area-detection |
Plot some of the results | plot_data_results(num_samples=2, fig_size=(5, 5), predict_config=predict_config, img_ch =3) | _____no_output_____ | Apache-2.0 | 3_Prediction.ipynb | dymaxionlabs/burned-area-detection |
The above plot shows that the best accuracy for KNN algorithm is obtained for **n_neighbors = 5** | fig, ax = plt.subplots()
ax.plot(num_cpu_list, training_times, 'ro')
ax.set_xlim([0, len(num_cpu_list)+1])
#plt.axis([0, len(num_cpu_list)+1, 0, max(training_times)+1])
plt.title("Search time vs #CPU Cores")
plt.xlabel("#CPU Cores")
plt.ylabel("search time [s]")
plt.show() | _____no_output_____ | MIT | notebooks/pawel_ueb01/03_Cross_validation_and_grid_search_bielski.ipynb | hhain/sdap17 |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
mnist = tf.keras.datasets.mnist # mnist is a dataset of 28x28 images of handwritten digits and their labels
(x_train, y_train),(x_test, y_test) = mnist.load_data() # unpacks images to x_trai... | _____no_output_____ | MIT | recurrent_neural_network_MNIST.ipynb | aadi-mishra/deepLearningProjects | |
pipegraph User Guide Rationale [scikit-learn](http://scikit-learn.org/stable/) provides a useful set of data preprocessors and machine learning models. The `Pipeline` object can effectively encapsulate a chain of transformers followed by final model. Other functions, like `GridSearchCV` can effectively use `Pipeline`... | import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
import matplotlib.pyplot as plt
X = 2*np.random.rand(100,1)-1
y... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Once we have some data ready, we instantiate the transformers and a regressor we want to fit: | scaler = MinMaxScaler()
polynomial_features = PolynomialFeatures()
linear_model = LinearRegression() | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
We define the steps that form the Pipeline object and then we instantiate such a Pipeline | steps = [('scaler', scaler),
('polynomial_features', polynomial_features),
('linear_model', linear_model)]
pipe = Pipeline(steps=steps) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Now we can pass this pipeline to `GridSearchCV`. When the `GridSearchCV` object is fitted, the search for the best combination for hyperparameters is performed according to the values provided in the `param_grid` parameter: | param_grid = {'polynomial_features__degree': range(1, 11),
'linear_model__fit_intercept': [True, False]}
grid_search_regressor = GridSearchCV(estimator=pipe, param_grid=param_grid, refit=True)
grid_search_regressor.fit(X, y); | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
And now we can check the results of fitting the Pipeline and the values of the hyperparameters: | y_pred = grid_search_regressor.predict(X)
plt.scatter(X, y)
plt.scatter(X, y_pred)
plt.show()
coef = grid_search_regressor.best_estimator_.get_params()['linear_model'].coef_
degree = grid_search_regressor.best_estimator_.get_params()['polynomial_features'].degree
print('Information about the parameters of the best est... | Information about the parameters of the best estimator:
degree: 5
coefficients: [[ 0. 443.10816501 -1849.10331869 3922.58622592 -4040.9186163
1619.79333825]]
| MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Pipeline weaknesses:From this example we can learn that `Pipeline` and `GridSearchCV` are very useful tools to consider when attempting to fit models. As far as the needs of the user can be satisfied by a set of transformers followed by a final model, this approach seems to be highly convenient. Additional advantages ... | from pipegraph import PipeGraphRegressor
X = 2*np.random.rand(100,1)-1
y = 40 * X**5 + 3*X*2 + 3*X + 3*np.random.randn(100,1)
scaler = MinMaxScaler()
linear_model = LinearRegression()
steps = [('scaler', scaler),
('linear_model', linear_model)]
pgraph = PipeGraphRegressor(steps=steps)
pgraph.fit(X, y) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
As the printed output shows, the internal links displayed by the `fit_connections` and `predict_connections` parameters are in line with those we saw in Figure 1 and those expected by a single path pipeline. As we did not specify these values, they were created by `PipeGRaphRegressor.__init__()` method as a comodity. W... | pgraph._pipegraph.fit_connections | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Figure 2 surely will help understading the syntax used by the connections dictionary. It goes like this:- The keys of the top level entries of the dictionary must be the same as those of the previously defined steps.- The values assocciated to these keys define the variables from other steps that are going to be consid... | y_pred = pgraph.predict(X)
plt.scatter(X, y, label='Original Data')
plt.scatter(X, y_pred, label='Predicted Data')
plt.title('Plots of original and predicted data')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('Index')
plt.ylabel('Value of Data')
plt.show() | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
`GridSearchCV` compatibility requirementsBoth `PipeGraphRegressor`and `PipeGraphClassifier` are compatible with `GridSearchCV` provided the last step can be scored, either:- by using `PipeGraphRegressor` or `PipeGraphClassifier` default scoring functions,- by implementing a custom scoring function capable of handling ... | from sklearn.preprocessing import PolynomialFeatures
X = 2*np.random.rand(100,1)-1
y = 40 * X**5 + 3*X*2 + 3*X + 3*np.random.randn(100,1)
scaler = MinMaxScaler()
polynomial_features = PolynomialFeatures()
linear_model = LinearRegression() | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Secondly, we define the steps and a ``param_grid`` dictionary as specified by `GridSearchCV`.In this case we just want to explore a few possibilities varying the degree of the polynomials and whether to use or not an intercept at the linear model. | steps = [('scaler', scaler),
('polynomial_features', polynomial_features),
('linear_model', linear_model)]
param_grid = {'polynomial_features__degree': range(1, 11),
'linear_model__fit_intercept': [True, False]} | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Now, we use ``PipeGraphRegressor`` as estimator for `GridSearchCV` and perform the ``fit`` and ``predict`` operations. As the last steps, a linear regressor from scikit-learn, already works with the default scoring functions, no extra efforts are needed to make it compatible with `GridSearchCV`. | pgraph = PipeGraphRegressor(steps=steps)
grid_search_regressor = GridSearchCV(estimator=pgraph, param_grid=param_grid, refit=True)
grid_search_regressor.fit(X, y)
y_pred = grid_search_regressor.predict(X)
plt.scatter(X, y)
plt.scatter(X, y_pred)
plt.show()
coef = grid_search_regressor.best_estimator_.get_params()['l... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
This example showed how to use `GridSearchCV` with `PipeGraphRegressor` in a simple single path workflow with default scoring functions. Let's explore in next section a more complex example. Multiple path workflow examplesUntill now, all the examples we showed displayed a single path sequence of steps and thus they co... | import pandas as pd
from pipegraph.base import ColumnSelector
from pipegraph.demo_blocks import CustomPower | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
We create an augmented ``X`` in which all data but ``y`` is concatenated. In this case, we concatenate ``X`` and ``sample_weight`` vector. | X = pd.DataFrame(dict(X=np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]),
sample_weight=np.array([0.01, 0.95, 0.10, 0.95, 0.95, 0.10, 0.10, 0.95, 0.95, 0.95, 0.01])))
y = np.array( [ 10, 4, 20, 16, 25 , -60, 85, 64, 81, 100, 150]) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Next we define the steps and we use `PipeGraphRegressor` as estimator for `GridSearchCV`. | scaler = MinMaxScaler()
polynomial_features = PolynomialFeatures()
linear_model = LinearRegression()
custom_power = CustomPower()
selector = ColumnSelector(mapping={'X': slice(0, 1),
'sample_weight': slice(1,2)})
steps = [('selector', selector),
('custom_power', custom_power... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Now, we have to define the connections of the model. We could have specified a dictionary containing the connections, but [as suggested by Joel Nothman](https://github.com/scikit-learn-contrib/scikit-learn-contrib/issues/28), scikit-learn users might find more convenient to use a method `inject` like in this example. L... | import inspect
print(inspect.getdoc(pgraph.inject)) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
`inject` allows to chain different calls to progressively describe all the connections needed in an easy to read manner: | (pgraph.inject(sink='selector', sink_var='X', source='_External', source_var='X')
.inject('custom_power', 'X', 'selector', 'sample_weight')
.inject('scaler', 'X', 'selector', 'X')
.inject('polynomial_features', 'X', 'scaler')
.inject('linear_model', 'X', 'polynomial_features')
.injec... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Then we define ``param_grid`` as expected by `GridSearchCV` to explore several possibilities of varying parameters. | param_grid = {'polynomial_features__degree': range(1, 3),
'linear_model__fit_intercept': [True, False],
'custom_power__power': [1, 5, 10, 20, 30]}
grid_search_regressor = GridSearchCV(estimator=pgraph, param_grid=param_grid, refit=True)
grid_search_regressor.fit(X, y)
y_pred = grid_search... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
This example showed how to solve current limitations of scikit-learn `Pipeline`:- Displayed a multipath workflow successfully implemented by **pipegraph**- Showed how to circumvent current limitations of standard `GridSearchCV`, in particular, the restriction on the number of input parameters- Showed the flexibility of... | from pipegraph.base import PipeGraphClassifier, Concatenator
from sklearn.datasets import load_iris
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
iris = load_iris()
X = iris.data
y = iris.target
scaler = MinMaxScaler()
gaussian_nb = GaussianNB(... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
In this example we use a `PipeGraphClassifier` because the result is a classification and we want to take advantage of scikit-learn default scoring method for classifiers. Once more, we use the `inject` chain of calls to define the connections. | pgraph = PipeGraphClassifier(steps=steps)
(pgraph.inject(sink='scaler', sink_var='X', source='_External', source_var='X')
.inject('gaussian_nb', 'X', 'scaler')
.inject('gaussian_nb', 'y', source_var='y')
.inject('svc', 'X', 'scaler')
.inject('svc', 'y', source_var='y')
.inject('concat... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
This example displayed complex data injections that are successfully managed by **pipegraph**. Example: Demultiplexor - multiplexorAn imaginative layout using a classifier to predict the cluster labels and fitting a separate model for each cluster. We will elaborate on this example in the examples that follow introdu... | from pipegraph.base import PipeGraphRegressor, Demultiplexer, Multiplexer
from sklearn.mixture import GaussianMixture
X_first = pd.Series(np.random.rand(100,))
y_first = pd.Series(4 * X_first + 0.5*np.random.randn(100,))
X_second = pd.Series(np.random.rand(100,) + 3)
y_second = pd.Series(-4 * X_second + 0.5*np.random.... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Instead of using ``inject`` as in previous example, in this one we are going to pass a dictionary describing the connections to PipeGraph constructor | connections = { 'scaler': {'X': 'X'},
'classifier': {'X': 'scaler'},
'demux': {'X': 'scaler',
'y': 'y',
'selection': 'classifier'},
'lm_0': {'X': ('demux', 'X_0'),
'y': ('demux', 'y_0')},
... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Example: Encapsulating several blocks into a PipeGraph and reusing itWe consider the previous example in which we had the following pipegraph model: We can be interested in using a fragment of the pipegraph, for example, those blocks marked with the circle (the Demultiplexer, the linear model collection, and the Mult... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.mixture import GaussianMixture
from sklearn.linear_model import LinearRegression
from pipegraph.base import PipeGraph, PipeGraphRegressor, Demultiplexer, Multiplexer
# Prepare some artific... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Now we can treat this PipeGraph as a reusable component and use it as a unitary step in another PipeGraph: | scaler = MinMaxScaler()
gaussian_mixture = GaussianMixture(n_components=3)
models = three_multiplexed_models
steps = [('scaler', scaler),
('classifier', gaussian_mixture),
('models', three_multiplexed_models), ]
connections = {'scaler': {'X': 'X'},
'classifier': {'X': 'scaler'},
... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Example: Dynamically built component using initialization parametersLast section showed how the user can choose to encapsulate several blocks into a PipeGraph and use it as a single unit in another PipeGraph. Now we will see how these components can be dynamically built on runtime depending on initialization parameter... | import inspect
from pipegraph.base import RegressorsWithParametrizedNumberOfReplicas
print(inspect.getsource(RegressorsWithParametrizedNumberOfReplicas)) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
As it can be seen from the source code, in this example we are basically interested in using a PipeGraph object whose `__init__` has different parameters than the usual ones. Thus, we subclass PipeGRaph and reimplement the `__init__` method. In doing so, we are capable of working out the structure of the steps and con... | scaler = MinMaxScaler()
gaussian_mixture = GaussianMixture(n_components=3)
models = RegressorsWithParametrizedNumberOfReplicas(number_of_replicas=3,
model_prototype=LinearRegression(),
model_parameters={})
steps = [... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Example: Dynamically built component using input signal values during the fit stageLast example showed how to grow a PipeGraph object programatically during runtime using the `__init__` method. In this example, we are going to show how we can change the internal structure of a PipeGraph object, not during initializati... | import inspect
from pipegraph.base import RegressorsWithDataDependentNumberOfReplicas
print(inspect.getsource(RegressorsWithDataDependentNumberOfReplicas)) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Again we subclass from parent `PipeGraph` class and implement a different `__init__`. In this example we won't make use of a `number_of_replicas` parameter, as it will be inferred from data during `fit` and thus we are satisfied by passing only those parameters allowing us to change the regressor models. As it can be s... | scaler = MinMaxScaler()
gaussian_mixture = GaussianMixture(n_components=3)
models = RegressorsWithDataDependentNumberOfReplicas(model_prototype=LinearRegression(), model_parameters={})
steps = [('scaler', scaler),
('classifier', gaussian_mixture),
('models', models), ]
connections = {'scaler': {'X':... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Example: GridSearch on dynamically built component using input signal valuesPrevious example showed how a PipeGraph object can be dynamically built on runtime depending on input signal values during fit. Now, in this example we will show how to use `GridSearchCV` to explore the best combination of hyperparameters. | from sklearn.model_selection import train_test_split
from pipegraph.base import NeutralRegressor
# We prepare some data
X_first = pd.Series(np.random.rand(100,))
y_first = pd.Series(4 * X_first + 0.5*np.random.randn(100,))
X_second = pd.Series(np.random.rand(100,) + 3)
y_second = pd.Series(-4 * X_second + 0.5*np.rand... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
To ease the calculation of the score for the GridSearchCV we add a neutral regressor as a last step, capable ofcalculating the score using a default scoring function. This is much more convenient than worrying about programminga custom scoring function for a block with an arbitrary number of inputs. | scaler = MinMaxScaler()
gaussian_mixture = GaussianMixture(n_components=3)
models = RegressorsWithDataDependentNumberOfReplicas(model_prototype=LinearRegression(), model_parameters={})
neutral_regressor = NeutralRegressor()
steps = [('scaler', scaler),
('classifier', gaussian_mixture),
('models', mod... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Using GridSearchCV to find the best number of clusters and the best regressors | from sklearn.model_selection import GridSearchCV
param_grid = {'classifier__n_components': range(2,10)}
gs = GridSearchCV(estimator=pgraph, param_grid=param_grid, refit=True)
gs.fit(X_train, y_train)
y_pred = gs.predict(X_train)
plt.scatter(X_train, y_train)
plt.scatter(X_train, y_pred)
print("Score:" , gs.score(X_tes... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Example: Alternative solutionNow we consider an alternative solution to the previous example. The solution already shown displayed the potentialof being able to morph the graph during fitting. A simpler approach is considered in this example by reusingcomponents and combining the classifier with the demultiplexed mod... | from pipegraph.base import ClassifierAndRegressorsBundle
print(inspect.getsource(ClassifierAndRegressorsBundle)) | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
As before, we built a custom block by subclassing PipeGraph and the modifying the `__init__` method to provide the parameters specifically needed for our purposes. Then we chain in the same PipeGraph the classifier, and the already available and known block for creating multiplexed models by providing parameters during... | scaler = MinMaxScaler()
classifier_and_models = ClassifierAndRegressorsBundle(number_of_replicas=6)
neutral_regressor = NeutralRegressor()
steps = [('scaler', scaler),
('bundle', classifier_and_models),
('neutral', neutral_regressor)]
connections = {'scaler': {'X': 'X'},
'bundle': {'X... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
Using GridSearchCV to find the best number of clusters and the best regressors | from sklearn.model_selection import GridSearchCV
param_grid = {'bundle__number_of_replicas': range(3,10)}
gs = GridSearchCV(estimator=pgraph, param_grid=param_grid, refit=True)
gs.fit(X_train, y_train)
y_pred = gs.predict(X_train)
plt.scatter(X_train, y_train)
plt.scatter(X_train, y_pred)
print("Score:" , gs.score(X_t... | _____no_output_____ | MIT | doc/User_Guide.ipynb | hannah83i/PipeGraph |
2. Acquire the Data Finding Data SourcesThere are three place to get onion price and quantity information by market. 1. **[Agmarket](http://agmarknet.nic.in/)** - This is the website run by the Directorate of Marketing & Inspection (DMI), Ministry of Agriculture, Government of India and provides daily price and arriva... | # Import the library we need, which is Pandas
import pandas as pd
# Read all the tables from the html document
AllTables = pd.read_html('MonthWiseMarketArrivalsJan2016.html')
# Let us find out how many tables has it found?
len(AllTables)
type(AllTables) | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Exercise 2Find the exact table of data we want in the list of AllTables? | AllTables[4] | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Get the exact tableTo read the exact table we need to pass in an identifier value which would identify the table. We can use the `attrs` parameter in read_html to do so. The parameter we will pass is the `id` variable | # So can we read our exact table
OneTable = pd.read_html('MonthWiseMarketArrivalsJan2016.html',
attrs = {'id' : 'dnn_ctr974_MonthWiseMarketArrivals_GridView1'})
# So how many tables have we got now
len(OneTable)
# Show the table of data identifed by pandas with just the first five rows
OneTable[0... | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
However, we have not got the header correctly in our dataframe. Let us see if we can fix this.To get help on any function just use `??` before the function to help. Run this function and see what additional parameter you need to define to get the header correctly | ??pd.read_html | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Exercise 3Read the html file again and ensure that the correct header is identifed by pandas? | OneTable = pd.read_html('MonthWiseMarketArrivalsJan2016.html', header = 0,
attrs = {'id' : 'dnn_ctr974_MonthWiseMarketArrivals_GridView1'}) | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Show the top five rows of the dataframe you have read to ensure the headers are now correct. | OneTable[0].head() | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Dataframe Viewing | # Let us store the dataframe in a df variable. You will see that as a very common convention in data science pandas use
df = OneTable[0]
# Shape of the dateset - number of rows & number of columns in the dataframe
df.shape
# Get the names of all the columns
df.columns
# Can we see sample rows - the top 5 rows
df.head(... | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
Downloading the Entire Month Wise Arrival Data | AllTable = pd.read_html('MonthWiseMarketArrivals.html', header = 0,
attrs = {'id' : 'dnn_ctr974_MonthWiseMarketArrivals_GridView1'})
AllTable[0].head()
??pd.DataFrame.to_csv
AllTable[0].columns
# Change the column names to simpler ones
AllTable[0].columns = ['market', 'month', 'year', 'quantity', ... | _____no_output_____ | MIT | time_series/2-Acquire.ipynb | tvquynh/TimeSeriesAnalysiswithPython |
nbdev tutorial> A step by step guide- image: images/nbdev_source.gif nbdev is a system for *exploratory programming*. See the [nbdev launch post](https://www.fast.ai/2019/12/02/nbdev/) for information about what that means. In practice, programming in this way can feel very different to the kind of programming many of... | #export
def say_hello(to):
"Say hello to somebody"
return f'Hello {to}!' | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
Add examples and tests It's a good idea to give an example of your function in action. Just include regular code cells, and they'll appear (with output) in the docs, e.g.: | say_hello("Sylvain") | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
Examples can output plots, images, etc, and they'll all appear in your docs, e.g.: | from IPython.display import display,SVG
display(SVG('<svg height="100"><circle cx="50" cy="50" r="40"/></svg>')) | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
You can also include tests: | assert say_hello("Jeremy")=="Hello Jeremy!" | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
You should also add markdown headings as you create your notebook; one benefit of this is that a table of contents will be created in the documentation automatically. Build lib Now you can create your python module. To do so, just run `nbdev_build_lib` from the terminal when anywhere in your project folder.```$ nbdev_... | #export
class HelloSayer:
"Say hello to `to` using `say_hello`"
def __init__(self, to): self.to = to
def say(self):
"Do the saying"
say_hello(self.to) | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
Document with show_doc However, methods aren't automatically documented. To add method docs, use `show_doc`:```pythonfrom nbdev.showdoc import *show_doc(HelloSayer.say)``` | from nbdev.showdoc import *
show_doc(HelloSayer.say) | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
And add some examples and/or tests: | o = HelloSayer("Alexis")
o.say() | _____no_output_____ | Apache-2.0 | nbs/tutorial.ipynb | vguerra/nbdev |
I've approached this problem as a regression problem and trained the model with the helps of LSTMs, details of the model architecture are furnished below.I've evaluated the model using 3 iterations of hold-out validation, the details of which are furnished below | from google.colab import drive
import pandas as pd
import numpy as np
drive.mount('/content/gdrive')
#Please mount it to appropriate directory where all the files are put
cd gdrive/My\ Drive/73Strings
#Constructing dataframe using dictionary.txt and sentiment_labels.txt
phrase_and_ids = pd.read_table('dictionary.txt',... | _____no_output_____ | MIT | Notebooks/2_Model_Training.ipynb | santosh-gokul/SentimentAnalysis |
Author : Devesh Kumar Task 4 : Prediction using Decision Tree Algorithm___ GRIP @ The Sparks Foundation____ Role : Data Science and Business Analytics [Batch May-2021] Table of Contents> - 1. Introduction.- 2. Importing Libraries.- 3. Fetching and loading data.- 4. Checking for null values.- 5. Plotting Pairplot.- 6. ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore') | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
**Fetching and loading data** | iris = pd.read_csv("/content/sample_data/Iris - Iris.csv") #loading the dataset in iris variable
iris.head()
iris.tail()
iris = iris.drop(['Id'], axis = 1) #dropping column 'Id'
iris
iris.shape | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
In iris dataset, 5 features and 150 datapoints are present. **Checking for Null Values** | iris.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 150 entries, 0 to 149
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 SepalLengthCm 150 non-null float64
1 SepalWidthCm 150 non-null float64
2 PetalLengthCm 150 non-null floa... | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
Here, we can see that no null values are present. | iris['Species'].value_counts() | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
From the above data we can say that, the iris dataset is a balanced dataset as the number of datapoints for every class are same. **Plotting Pairplot** | sns.set_style("whitegrid")
sns.pairplot(iris,hue="Species",size=3);
plt.show() | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
**Splitting The Data** | X = iris.iloc[ : , : -1]
y = iris.iloc[ : , -1 ]
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
**Decision Tree** **Training and fitting the model** | from sklearn.tree import DecisionTreeClassifier
tree_clf=DecisionTreeClassifier()
tree_clf.fit(x_train,y_train)
y_pred = tree_clf.predict(x_test)
y_pred
pd.DataFrame(y_pred, y_test) | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
**Model Evaluation** | from sklearn.metrics import accuracy_score
print(accuracy_score(y_test, y_pred))
from sklearn.metrics import classification_report
print(classification_report(y_test, y_pred)) | precision recall f1-score support
Iris-setosa 1.00 1.00 1.00 16
Iris-versicolor 1.00 0.94 0.97 18
Iris-virginica 0.92 1.00 0.96 11
accuracy 0.98 45
macro avg 0.97 0... | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
**Graphical Visualization** | # Import necessary libraries for graph viz
from sklearn.externals.six import StringIO
from IPython.display import Image
from sklearn.tree import export_graphviz
import pydotplus
# Visualize the graph
dot_data = StringIO()
export_graphviz(tree_clf, out_file=dot_data, feature_names=iris.columns[:-1],
... | _____no_output_____ | MIT | Prediction using Decision Tree Algorithm/Decision__Tree_(iris_dataset).ipynb | demaria11/Spark_Projects |
04 - Full waveform inversion with Devito and scipy.optimize.minimize IntroductionIn this tutorial we show how [Devito](http://www.opesci.org/devito-public) can be used with [scipy.optimize.minimize](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html) to solve the FWI gradient based mini... | #NBVAL_IGNORE_OUTPUT
from examples.seismic import Model, demo_model
import numpy as np
# Define the grid parameters
def get_grid():
shape = (101, 101) # Number of grid point (nx, nz)
spacing = (10., 10.) # Grid spacing in m. The domain size is now 1km by 1km
origin = (0., 0.) # Need origin to defin... | _____no_output_____ | MIT | examples/seismic/tutorials/04_scipy_optimise.ipynb | jrt54/total_variation |
Create operators for gradient based inversionTo perform the inversion we are going to use [scipy.optimize.minimize(method=’L-BFGS-B’)](https://docs.scipy.org/doc/scipy/reference/optimize.minimize-lbfgsb.htmloptimize-minimize-lbfgsb).First we define the functional, ```f```, and gradient, ```g```, operator (i.e. the fun... | from devito import Function, clear_cache
# Create FWI gradient kernel for a single shot
def fwi_gradient_i(x, param):
# Need to clear the workers cache.
clear_cache()
# Get the current model and the shot data for this worker.
model0 = get_initial_model()
model0.m.data[:] = x.astype(np.float32).res... | _____no_output_____ | MIT | examples/seismic/tutorials/04_scipy_optimise.ipynb | jrt54/total_variation |
Next we define the global functional and gradient function that sums the contributions to f and g for each shot of data. | def fwi_gradient(x, param):
# Initialize f and g.
param['shot_id'] = 0
f, g = fwi_gradient_i(x, param)
# Loop through all shots summing f, g.
for i in range(1, param['nshots']):
param['shot_id'] = i
f_i, g_i = fwi_gradient_i(x, param)
f += f_i
g[:] += g_i
... | _____no_output_____ | MIT | examples/seismic/tutorials/04_scipy_optimise.ipynb | jrt54/total_variation |
FWI with L-BFGS-BEquipped with a function to calculate the functional and gradient, we are finally ready to call ```scipy.optimize.minimize```. | #NBVAL_SKIP
# Change to the WARNING log level to reduce log output
# as compared to the default DEBUG
from devito import configuration
configuration['log_level'] = 'WARNING'
# Set up a dictionary of inversion parameters.
param = {'t0': 0.,
'tn': 1000., # Simulation lasts 1 second (1000 ms)
... | _____no_output_____ | MIT | examples/seismic/tutorials/04_scipy_optimise.ipynb | jrt54/total_variation |
While we are resolving the circle at the centre of the domain there are also lots of artifacts throughout the domain. | #NBVAL_SKIP
import matplotlib.pyplot as plt
# Plot objective function decrease
plt.figure()
plt.loglog(relative_error)
plt.xlabel('Iteration number')
plt.ylabel('True relative error')
plt.title('Convergence')
plt.show() | _____no_output_____ | MIT | examples/seismic/tutorials/04_scipy_optimise.ipynb | jrt54/total_variation |
End-to-End Machine Learning ProjectIn this chapter you will work through an example project end to end, pretending to be a recently hired data scientist at a real estate company. Here are the main steps you will go through:1. Look at the big picture2. Get the data3. Discover and visualize the data to gain insights.4. ... | import os
import tarfile
import urllib
DOWNLOAD_ROOT = "https://raw.githubusercontent.com/ageron/handson-ml2/master/"
HOUSING_PATH = os.path.join("datasets", "housing")
HOUSING_URL = DOWNLOAD_ROOT + "datasets/housing/housing.tgz"
def fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_PATH):
"""
... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Take a quick look at the Data StructureEach row represents one district. There are 10 attributes:```longitude, latitude, housing_median_age, total_rooms, total_bedrooms, population, households, median_income, median_house_value, ocean_proximity```The `info()` method is useful to give a quick description of the data. | housing.head()
housing.info()
housing["ocean_proximity"].value_counts()
housing.describe()
%matplotlib inline
import matplotlib.pyplot as plt
housing.hist(bins=50, figsize=(20, 15))
plt.show(); | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
> 🔑 **Note:** The `hist()` method relies on Matplotlib, which in turn relies on a user-specified graphical backend to draw on your screen. The simplest option is to use Jupyter's magic command `%matplotlib inline`. This tells jupyter to set up Matplotlib so that it uses Jupyter's own backend. Note that calling `plot()... | from sklearn.model_selection import train_test_split
train_set, test_set = train_test_split(housing, test_size=0.2, random_state=42)
train_set.shape, test_set.shape
from sklearn.model_selection import StratifiedShuffleSplit
housing["income_cat"] = pd.cut(housing["median_income"],
bins=[0.... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Discover and Visualize the Data to Gain More InsightsSo far you have only taken a quick glance at the data to get a general understanding of the kind of data you are manipulating. Now the goal is to go into a lttle more depth.First, make sure you have put the test set aside and you are only exploring the training data... | housing = strat_train_set.copy() | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Visualizing Geopgraphical DataSince there is geographical information (latitude and longitude), it is a good idea to create a scatterplot pf all districts to visualize the data. | housing.plot(kind="scatter", x="longitude", y="latitude");
# Setting the alpha optin to 0.1 makes it easier to visualize the places where there is a high -density of data points.
housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.1); | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Now from the above graph, we can clearly see the high-density areas. Our brains are very good at spotting patterns in pictures, but you may need to play around with visualization parameters to make the patterns stand out.Now let's look at the housing prices. The radius of each circle represents the district's populaito... | housing.plot(kind="scatter", x="longitude", y="latitude", alpha=0.4,
s=housing["population"]/100, label="population", figsize=(10, 7),
c="median_house_value", cmap=plt.get_cmap("jet"), colorbar=True)
plt.legend(); | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Looking for CorrelationsSince the dataset is not too large, you can easily compute the *standard correlation coeffecient* (also known as *Pearson's r*) between every pair of attributes using the `corr()` method | corr_matrix = housing.corr()
# Now let's look at how much each attribute correlates with the median house value
corr_matrix["median_house_value"].sort_values(ascending=False) | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
The Standard Correlation CoeffecientThe correlation coeffecient ranges from -1 to 1. When it is close to 1, it means that there is strong positive correlation. While, when the coeffecient is close to -1, it means there is a strong negative correlation. Finally coeffecients close to 0 mean that there is no linear corre... | from pandas.plotting import scatter_matrix
attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"]
scatter_matrix(housing[attributes], figsize=(12, 12));
# The most promising attribute to predict the median house value is the median income
housing.plot(kind="scatter", x="median_income... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
This plot reveals a few things:1. The correlation is indeed very strong as you can see clearly the upward trend, and the points are not too dispersed.2. The price cap that we noticed earlier is clearly visible as a horizontal line at $500,000. There are a few more less-obvious lines that you may want to remove to preve... | housing["rooms_per_household"] = housing["total_rooms"]/housing["households"]
housing["bedrooms_per_room"] = housing["total_bedrooms"]/housing["total_rooms"]
housing["population_per_household"] = housing["population"]/housing["households"]
corr_matrix = housing.corr()
corr_matrix["median_house_value"].sort_values(ascen... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Hey, not bad! The new attributes have some more correlation Prepare the Data for Machine Learning AlgorithmsIt's time to prepare the data for your Machine Learning algorithm. Instead of doing this manually, you should write functions for this purpose, for several good reasons:- This will allow you to reproduce these t... | # Let's revert to a clean training set
housing = strat_train_set.drop("median_house_value", axis=1)
housing_labels = strat_train_set["median_house_value"].copy() | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Data CleaningMost Machine Learning algorithms cannot work with data that have missing features, so let's create a few functions to take care of them. We say earlier that the `total_bedrooms` attribute has some missing values, so let's fix this. You have three options to do so:1. Get rid of the corresponding districts.... | # housing.dropna(subset=["total_bedrooms"])
# housing.drop("total_bedrooms", axis=1)
# median = housing["total_bedrooms"].median()
# housing["total_bedrooms"].fillna(median, inplace=True) | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
But we'll be using the Scikit-Learning platform.Scikit-Learn provides a handy class to take care of the missing values: `SimpleImputer`. | from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy="median")
# Since the median can be computed only on numerical attributes, drop the ocean_proximity attribute which is a String
housing_num = housing.drop("ocean_proximity", axis=1)
imputer.fit(housing_num)
X = imputer.transform(housing_num)
# Th... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 16512 entries, 12655 to 19773
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 longitude 16512 non-null float64
1 latitude 16512 non-null float64
2 housing... | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Handling Text and Categorical AttributesSo far we have only dealt with numerical attributes, but now let's look at text attributes. In this dataset, there is just one: the `ocean_proximity` attribute. Let's look at its value fo first 10 instances: | # First 10 instances
housing_cat = housing[["ocean_proximity"]]
housing_cat.head(10)
housing["ocean_proximity"].value_counts()
# It's not arbitary text. Therefore, it is categorical text.
# One hot encoding the data
from sklearn.preprocessing import OneHotEncoder
cat_enc = OneHotEncoder()
housing_cat_one_hot = cat_enc.... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Custom TrasformersAlthough Scikit-Learn provides many useful transformers, you will need to write your own for tasks such as custom cleanup operations or combining specific attributes. You will want your transformer to work seamlessely with Scikit-Learn functionalitites (such as `pipelines`), all you need to do is cre... | from sklearn.base import BaseEstimator, TransformerMixin
rooms_ix, bedrooms_ix, population_ix, households_ix = 3, 4, 5, 6
class CombinedAttributeAdder(BaseEstimator, TransformerMixin):
def __init__(self, add_bedrooms_per_room=True):
self.add_bedrooms_per_room = add_bedrooms_per_room
def fit(self, X, y... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Feature ScalingOne of the most imprtant features you need to apply to your data is *feature scaling*. With a few exceptions, Machine Learning algorithms don't perform well numerical attributes have very different scales. There are two common ways to get all the attributes to have the same scale, namely, *min-max scali... | from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
num_pipeline = Pipeline([
('imputer', SimpleImputer(strategy="median")),
('attribs_adder', CombinedAttributeAdder()),
('std_scaler', StandardScaler())
])
housing_num_tr = num_pipeline.fit_transform(housing_num)
housing
f... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Select and Train a ModelAt last!😃 You framed the problem, you got your data and explored it, you sampled a training set and a test set, and you wrote transformation pipelines to clean up and prepare your data for Machine learning slgorithms automatically. You are now ready to select and train a Machine Learning Model... | # 1. Linear Regression model
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(housing_prepared, housing_labels)
from sklearn.metrics import mean_squared_error
lin_reg_predictions = lin_reg.predict(housing_prepared)
lin_reg_predictions[:10]
lin_reg_results = np.sqrt(mean_square... | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
Better Evaluation using Cross-ValidationA great feature of Scikit-Learn is its *K-fold cross-validaation* feature. The following code randomy splits the training set into 10 distinct subsets called folds, then it trains and evaluates the Decision Tree model 10 times, picking a different fold for evaluation every time ... | from sklearn.model_selection import cross_val_score
scores = cross_val_score(tree_reg, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10)
tree_rmse_scores = np.sqrt(-scores)
tree_rmse_scores.mean() | _____no_output_____ | Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
> 🔑 **Note:** Scikit-Learn's cross-validation features expect a utility function (grater is better) rather than a cost function (lower is better), so the scoring function is actually the opposite of MSE (i.e., a negative value), which is why the preceding code computes -scores before calculating the square root. | # Function to display the scores of any model
from sklearn.model_selection import cross_val_score
def display_scores(model):
scores = cross_val_score(model, housing_prepared, housing_labels, scoring="neg_mean_squared_error", cv=10)
rmse_scores = np.sqrt(-scores)
print(f"Scores: {rmse_scores}")
print(f"... | Scores: [51449.33449009 49166.9957334 46702.81301729 51854.00681753
47616.05406059 51682.33174969 52711.31825207 49689.17571866
48845.21581467 53732.57696017]
Scores: 50344.98226141429
Standard deviation: 2171.1765538076525
| Apache-2.0 | Hands_On_ML_Book/Chapter_2/End-to-End_ML_Project.ipynb | ARGF0RCE/Hands-On-ML-Made-Easy |
$P_\ell(k)$ measurements for SIMBIG CMASSIn this notebook, I demonstrate how we measure the power spectrum multipoles, $P_\ell(k)$ from the forward modeled SIMBIG CMASS mocks | import os, time
import numpy as np
from simbig import halos as Halos
from simbig import galaxies as Galaxies
from simbig import forwardmodel as FM
from simbig import obs as CosmoObs
# --- plotting ---
import matplotlib as mpl
import matplotlib.pyplot as plt
#mpl.rcParams['text.usetex'] = True
mpl.rcParams['font.family... | _____no_output_____ | MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
Forward model SIMBIG CMASS 1. Read in `Quijote` Halo CatalogI'm using `i=1118`th cosmology in the LHC because that's the close to the fiducial cosmology | # read in halo catalog
halos = Halos.Quijote_LHC_HR(1118, z=0.5)
print('Om, Ob, h, ns, s8:')
print(Halos.Quijote_LHC_cosmo(1118)) | Om, Ob, h, ns, s8:
(0.2671, 0.03993, 0.6845, 0.96030000000000004, 0.78549999999999998)
| MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
2. Populate halos with HODWe'll use best-fit HOD parameters for CMASS from Reid et al. (2014) | theta_hod = Galaxies.thetahod_literature('reid2014_cmass')
print(theta_hod)
# apply HOD
hod = Galaxies.hodGalaxies(halos, theta_hod, seed=0) | {'logMmin': 13.03, 'sigma_logM': 0.38, 'logM0': 13.27, 'logM1': 14.08, 'alpha': 0.76}
| MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
3. Apply forward model | # apply forward model without veto mask, without fiber collisions
gals = FM.BOSS(hod, sample='cmass-south', seed=0, veto=False, fiber_collision=False, silent=False) | ..applying angular mask takes 1 sec
..applying additional selection
..footprint covers 0.048 of sky
| MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
Measure $P_\ell(k)$Now we'll measure $P_\ell(k)$ for SIMBIG CMASS. First we'll measure $P_\ell$ for a periodic box for sanity check | # apply RSD to hod catalog in a box
pos_rsd = FM.Box_RSD(hod, LOS=[0,0,1], Lbox=1000)
hod_rsd = hod.copy()
hod_rsd['Position'] = pos_rsd
plk_box = CosmoObs.Plk_box(hod_rsd) | _____no_output_____ | MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
Now lets measure $P_\ell$ for SIMBIG CMASS. This requires first constructing a random catalog. | # get randoms
rand = FM.BOSS_randoms(gals, sample='cmass-south', veto=False)
# measure plk
plk = CosmoObs.Plk_survey(gals, rand, Ngrid=360, dk=0.005, P0=1e4, silent=False) | alpha = 0.046360
assuming fiducial cosmology
| MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
$P_\ell$ is calcaulated assuming a fiducial cosmology (same as in observations). However, the fiducial cosmology is different than the true cosmology of the simulation. So there will be discrepancies in the SIMBIG CMASS $P_\ell$ and $P_\ell$ calculated for the periodic box. As a sanity check, lets calculate SIMBIG CMAS... | _plk_realcosmo = CosmoObs.Plk_survey(gals, rand, cosmo=gals.cosmo, Ngrid=360, dk=0.005, P0=1e4, silent=False)
fig = plt.figure(figsize=(5,5))
sub = fig.add_subplot(111)
sub.plot(plk_box[0], plk_box[1], c='k', ls=':', label='Periodic Box')
sub.plot(plk[0], plk[1], c='k', label='SIMBIG CMASS')
sub.plot(_plk_realcosmo[0],... | _____no_output_____ | MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
SIMBIG CMASS $P_\ell$ measured using the true cosmology is in good agreement with the periodic box. $P_\ell$ with different levels of survey realismThe comparison above only imposes survey geometry. Lets check that everything looks sensible when we impose veto mask and fiber collisions | # apply forward model without veto mask, without fiber collisions
gals_veto = FM.BOSS(hod, sample='cmass-south', seed=0, veto=True, fiber_collision=False, silent=False)
rand_veto = FM.BOSS_randoms(gals_veto, veto=True, sample='cmass-south')
plk_veto = CosmoObs.Plk_survey(gals_veto, rand_veto, Ngrid=360, dk=0.005, P0=1e... | _____no_output_____ | MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
The normalization difference between the $P_\ell$ with only survey geometry and $P_\ell$ with survey geometry + veto mask is an expected systematic of the veto mask with many small scale features ([de Mattia+2019](https://ui.adsabs.harvard.edu/abs/2019JCAP...08..036D/abstract), [de Mattia+2021](https://ui.adsabs.harvar... | dat_dir = '/tigress/chhahn/simbig/'
k_cmass = np.loadtxt(os.path.join(dat_dir, 'obs.cmass_sgc.k.dat'), skiprows=1)
p0k_cmass_wall = np.loadtxt(os.path.join(dat_dir, 'obs.cmass_sgc.p0k.w_all.dat'), skiprows=1)
p2k_cmass_wall = np.loadtxt(os.path.join(dat_dir, 'obs.cmass_sgc.p2k.w_all.dat'), skiprows=1)
p4k_cmass_wall = ... | _____no_output_____ | MIT | cmass/nb/plk_0_simbig_plk_demo.ipynb | muntazirabidi/boss-sbi |
How To Break Into the FieldNow you have had a closer look at the data, and you saw how I approached looking at how the survey respondents think you should break into the field. Let's recreate those results, as well as take a look at another question. | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import HowToBreakIntoTheField as t
%matplotlib inline
df = pd.read_csv('./survey_results_public.csv')
schema = pd.read_csv('./survey_results_schema.csv')
df.head() | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Question 1**1.** In order to understand how to break into the field, we will look at the **CousinEducation** field. Use the **schema** dataset to answer this question. Write a function called **get_description** that takes the **schema dataframe** and the **column** as a string, and returns a string of the descripti... | def get_description(column_name, schema=schema):
'''
INPUT - schema - pandas dataframe with the schema of the developers survey
column_name - string - the name of the column you would like to know about
OUTPUT -
desc - string - the description of the column
'''
desc = list(s... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
The question we have been focused on has been around how to break into the field. Use your **get_description** function below to take a closer look at the **CousinEducation** column. | get_description('CousinEducation') | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Question 2**2.** Provide a pandas series of the different **CousinEducation** status values in the dataset. Store this pandas series in **cous_ed_vals**. If you are correct, you should see a bar chart of the proportion of individuals in each status. If it looks terrible, and you get no information from it, then you... | cous_ed_vals = df.CousinEducation.value_counts()#Provide a pandas series of the counts for each CousinEducation status
cous_ed_vals # assure this looks right
# The below should be a bar chart of the proportion of individuals in your ed_vals
# if it is set up correctly.
(cous_ed_vals/df.shape[0]).plot(kind="bar");
plt... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
We definitely need to clean this. Above is an example of what happens when you do not clean your data. Below I am using the same code you saw in the earlier video to take a look at the data after it has been cleaned. | possible_vals = ["Take online courses", "Buy books and work through the exercises",
"None of these", "Part-time/evening courses", "Return to college",
"Contribute to open source", "Conferences/meet-ups", "Bootcamp",
"Get a job as a QA tester", "Participate in online c... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Question 4**4.** I wonder if some of the individuals might have bias towards their own degrees. Complete the function below that will apply to the elements of the **FormalEducation** column in **df**. | def higher_ed(formal_ed_str):
'''
INPUT
formal_ed_str - a string of one of the values from the Formal Education column
OUTPUT
return 1 if the string is in ("Master's degree", "Doctoral", "Professional degree")
return 0 otherwise
'''
if formal_ed_str in ("Master's d... | _____no_output_____ | MIT | lessons/CRISP_DM/How To Break Into the Field - Solution .ipynb | vishalwaka/DSND_Term2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.