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
Random Forest ClassifierThe Random forest or Random Decision Forest is a supervised Machine learning algorithm used for classification, regression, and other tasks using decision trees.The Random forest classifier creates a set of decision trees from a randomly selected subset of the training set. It is basically a set...
from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=100) clf.fit(x_train, y_train) print("Accuracy Score:", str(round(clf.score(x_test, y_test), 4) * 100) + '%') print('\nClassification Random Forest:\n', classification_report(y_test, clf.predict(x_test)))
Classification Random Forest: precision recall f1-score support 0 0.75 0.64 0.69 3292 1 0.76 0.84 0.80 4417 accuracy 0.76 7709 macro avg 0.75 0.74 0.74 7709 weighted avg ...
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
Now let's visualize our classification report:
plot_classification_report(classification_report(y_test, clf.predict(x_test)), title='Random Forest Classification Report')
_____no_output_____
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
SVM ModelSupport vector machines (SVMs) are a set of supervised learning methods used for classification, regression and outliers detection.The advantages of support vector machines are: + Effective in high dimensional spaces. + Still effective in cases where number of dimensions is greater than the number of sam...
from sklearn import svm SVM = svm.SVC(C=1.0, kernel='linear', degree=3, gamma='auto', probability=True) SVM.fit(x_train, y_train) print("Accuracy Score:", str(round(SVM.score(x_test, y_test), 4) * 100) + '%') print('\nClassification SVM:\n', classification_report(y_test, SVM.predict(x_test))) plot_classification_repo...
_____no_output_____
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
Comparison of Models A useful tool when predicting the probability of a binary outcome is the Receiver Operating Characteristic curve, or ROC curve.It is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) for a number of different candidate threshold values between 0.0 and 1.0. Put anothe...
from sklearn import metrics from sklearn.metrics import roc_curve, auc fprKNN, tprKNN, thresholdsKNN = metrics.roc_curve(y_test, knn.predict_proba(x_test)[:, 1]) fprLR, tprLR, thresholdsLR = metrics.roc_curve(y_test, logit.predict_proba(x_test)[:, 1]) fprCLF, tprCLF, thresholdCLF = metrics.roc_curve(y_test, clf.predic...
_____no_output_____
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
Based on these data, we can conclude that the best model so far is a **Random Forest Model** with `AUC = 83.5%` and `Accuracy Score = 75.56%`.Let's save this model:
with open('RFModel.pickle', 'wb') as m: pickle.dump(logit, m)
_____no_output_____
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
Let's check if everything is loaded correctly:
with open('RFModel.pickle', 'rb') as m: rf = pickle.load(m) print("Random Forest Accuracy Score:", str(round(clf.score(x_test, y_test), 4) * 100) + '%')
Random Forest Accuracy Score: 75.56%
MIT
Part II - Sentiment Analysis Classifications - Review and Comparison.ipynb
JackShen1/sentimento
Run source tutorialhttps://www.geeksforgeeks.org/machine-learning-for-anomaly-detection/
import matplotlib.font_manager from pyod.models.knn import KNN from pyod.utils.data import generate_data, get_outliers_inliers # [1] CREATE SYNTHETIC DATA npoints = 300 # Generating a random dataset with two features X_train, y_train = generate_data(n_train = npoints, train_only = True, ...
_____no_output_____
MIT
data/pyodKNN.DummyDataset-anomaly_detection.ipynb
therobotacademy/kaggle-anomaly-detection
Lesson 7: Pattern Challenges In this set of exercises, we'll play with number patterns, shape patterns, and other types of repetition and variation. This is to get you thinking more flexibly about what you can do with code, so that you can better apply it to practical situations later. FibonacciThe fibonacci sequenc...
print "Hello\nJenny"
Hello Jenny
Apache-2.0
lesson7exercises.ipynb
jennybrown8/python-notebook-coding-intro
Point cloudThis tutorial demonstrates basic usage of a point cloud. Visualize point cloudThe first part of the tutorial reads a point cloud and visualizes it.
print("Load a ply point cloud, print it, and render it") ply_point_cloud = o3d.data.PLYPointCloud() pcd = o3d.io.read_point_cloud(ply_point_cloud.path) print(pcd) print(np.asarray(pcd.points)) o3d.visualization.draw_geometries([pcd], zoom=0.3412, front...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
`read_point_cloud` reads a point cloud from a file. It tries to decode the file based on the extension name. For a list of supported file types, refer to [File IO](file_io.ipynb).`draw_geometries` visualizes the point cloud. Use a mouse/trackpad to see the geometry from different view points.It looks like a dense surfa...
print("Downsample the point cloud with a voxel of 0.05") downpcd = pcd.voxel_down_sample(voxel_size=0.05) o3d.visualization.draw_geometries([downpcd], zoom=0.3412, front=[0.4257, -0.2125, -0.8795], lookat=[2.6172, 2.04...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Vertex normal estimationAnother basic operation for point cloud is point normal estimation.Press `N` to see point normals. The keys `-` and `+` can be used to control the length of the normal.
print("Recompute the normal of the downsampled point cloud") downpcd.estimate_normals( search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30)) o3d.visualization.draw_geometries([downpcd], zoom=0.3412, front=[0.4257, -0.2125, -0.87...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
`estimate_normals` computes the normal for every point. The function finds adjacent points and calculates the principal axis of the adjacent points using covariance analysis.The function takes an instance of `KDTreeSearchParamHybrid` class as an argument. The two key arguments `radius = 0.1` and `max_nn = 30` specifies...
print("Print a normal vector of the 0th point") print(downpcd.normals[0])
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
To check out other variables, please use `help(downpcd)`. Normal vectors can be transformed as a numpy array using `np.asarray`.
print("Print the normal vectors of the first 10 points") print(np.asarray(downpcd.normals)[:10, :])
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Check [Working with NumPy](working_with_numpy.ipynb) for more examples regarding numpy arrays. Crop point cloud
print("Load a polygon volume and use it to crop the original point cloud") demo_crop_data = o3d.data.DemoCropPointCloud() pcd = o3d.io.read_point_cloud(demo_crop_data.point_cloud_path) vol = o3d.visualization.read_selection_polygon_volume(demo_crop_data.cropped_json_path) chair = vol.crop_point_cloud(pcd) o3d.visualiza...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
`read_selection_polygon_volume` reads a json file that specifies polygon selection area. `vol.crop_point_cloud(pcd)` filters out points. Only the chair remains. Paint point cloud
print("Paint chair") chair.paint_uniform_color([1, 0.706, 0]) o3d.visualization.draw_geometries([chair], zoom=0.7, front=[0.5439, -0.2333, -0.8060], lookat=[2.4615, 2.1331, 1.338], up=...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
`paint_uniform_color` paints all the points to a uniform color. The color is in RGB space, [0, 1] range. Point cloud distanceOpen3D provides the method `compute_point_cloud_distance` to compute the distance from a source point cloud to a target point cloud. I.e., it computes for each point in the source point cloud th...
# Load data demo_crop_data = o3d.data.DemoCropPointCloud() pcd = o3d.io.read_point_cloud(demo_crop_data.point_cloud_path) vol = o3d.visualization.read_selection_polygon_volume(demo_crop_data.cropped_json_path) chair = vol.crop_point_cloud(pcd) dists = pcd.compute_point_cloud_distance(chair) dists = np.asarray(dists) i...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Bounding volumesThe `PointCloud` geometry type has bounding volumes as all other geometry types in Open3D. Currently, Open3D implements an `AxisAlignedBoundingBox` and an `OrientedBoundingBox` that can also be used to crop the geometry.
aabb = chair.get_axis_aligned_bounding_box() aabb.color = (1, 0, 0) obb = chair.get_oriented_bounding_box() obb.color = (0, 1, 0) o3d.visualization.draw_geometries([chair, aabb, obb], zoom=0.7, front=[0.5439, -0.2333, -0.8060], ...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Convex hullThe convex hull of a point cloud is the smallest convex set that contains all points. Open3D contains the method `compute_convex_hull` that computes the convex hull of a point cloud. The implementation is based on [Qhull](http://www.qhull.org/).In the example code below we first sample a point cloud from a ...
bunny = o3d.data.BunnyMesh() mesh = o3d.io.read_triangle_mesh(bunny.path) mesh.compute_vertex_normals() pcl = mesh.sample_points_poisson_disk(number_of_points=2000) hull, _ = pcl.compute_convex_hull() hull_ls = o3d.geometry.LineSet.create_from_triangle_mesh(hull) hull_ls.paint_uniform_color((1, 0, 0)) o3d.visualizatio...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
DBSCAN clusteringGiven a point cloud from e.g. a depth sensor we want to group local point cloud clusters together. For this purpose, we can use clustering algorithms. Open3D implements DBSCAN [\[Ester1996\]](../reference.htmlEster1996) that is a density based clustering algorithm. The algorithm is implemented in `clu...
ply_point_cloud = o3d.data.PLYPointCloud() pcd = o3d.io.read_point_cloud(ply_point_cloud.path) with o3d.utility.VerbosityContextManager( o3d.utility.VerbosityLevel.Debug) as cm: labels = np.array( pcd.cluster_dbscan(eps=0.02, min_points=10, print_progress=True)) max_label = labels.max() print(f"po...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
**Note:** This algorithm precomputes all neighbors in the epsilon radius for all points. This can require a lot of memory if the chosen epsilon is too large. Plane segmentationOpen3D also supports segmententation of geometric primitives from point clouds using RANSAC. To find the plane with the largest support in ...
pcd_point_cloud = o3d.data.PCDPointCloud() pcd = o3d.io.read_point_cloud(pcd_point_cloud.path) plane_model, inliers = pcd.segment_plane(distance_threshold=0.01, ransac_n=3, num_iterations=1000) [a, b, c, d] = plane_model print(f"Plane eq...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Hidden point removalImagine you want to render a point cloud from a given view point, but points from the background leak into the foreground because they are not occluded by other points. For this purpose we can apply a hidden point removal algorithm. In Open3D the method by [\[Katz2007\]](../reference.htmlKatz2007) ...
print("Convert mesh to a point cloud and estimate dimensions") armadillo = o3d.data.ArmadilloMesh() mesh = o3d.io.read_triangle_mesh(armadillo.path) mesh.compute_vertex_normals() pcd = mesh.sample_points_poisson_disk(5000) diameter = np.linalg.norm( np.asarray(pcd.get_max_bound()) - np.asarray(pcd.get_min_bound())...
_____no_output_____
MIT
docs/jupyter/geometry/pointcloud.ipynb
pmokeev/Open3D
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) school_data_to_load = "Resources/schools_complete.csv" student_data_to_load = "Resources/students_complete.csv" # Read School and Student Data File and store into Pandas DataFrames school_data = pd.read_csv(school_data_to_load) stu...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
District Summary* Calculate the total number of schools* Calculate the total number of students* Calculate the total budget* Calculate the average math score * Calculate the average reading score* Calculate the percentage of students with a passing math score (70 or greater)* Calculate the percentage of students with ...
number_of_schools = len(school_data["School ID"].unique()) number_of_schools number_of_students = len(student_data["Student ID"].unique()) number_of_students total_budget = school_data["budget"].sum() total_budget avg_math_score = student_data["math_score"].mean() avg_math_score avg_read_score = student_data["reading_s...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
School Summary * Create an overview table that summarizes key metrics about each school, including: * School Name * School Type * Total Students * Total School Budget * Per Student Budget * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * % Overall Passing (The percentage of ...
# Strategy: school_data already has the first few columns. Format school_data, then calculate # additional series columns separately, then add each series column to the formatted dataframe # start with formatting school_data. Important to set index for future merges school_summary = (school_data.set_index("school_na...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Top Performing Schools (By % Overall Passing) * Sort and display the top five performing schools by % overall passing.
(school_summary.sort_values("% Overall Passing", ascending=False) .head(5) )
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Bottom Performing Schools (By % Overall Passing) * Sort and display the five worst-performing schools by % overall passing.
(school_summary.sort_values("% Overall Passing", ascending=True) .head(5) )
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Math Scores by Grade * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. * Create a pandas series for each grade. Hint: use a conditional statement. * Group each series by school * Combine the series into a dataframe * Optional: give ...
# Index student_data and get only relevant columns score_by_grade = student_data[["school_name", "grade", "math_score"]].set_index("school_name") # Create initial math_by_school dataframe, then create additional series and append them to # the dataframe math_by_school = (score_by_grade.loc[score_by_grade["grade"] ==...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Reading Score by Grade * Perform the same operations as above for reading scores
score_by_grade = student_data[["school_name", "grade", "reading_score"]].set_index("school_name") # Create initial read_by_school dataframe, then create additional series and append them to # the dataframe read_by_school = (score_by_grade.loc[score_by_grade["grade"] == "9th"] ...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Scores by School Spending * Create a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following: * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Pa...
# Use school_summary_unformatted dataframe that still has numeric columns as float # Define the cut parameters series_to_cut = school_summary_unformatted["Per Student Budget"] bins_to_fill = [0, 584.9, 629.9, 644.9, 675.9] bin_labels = ["<$584", "$585-629", "$630-644", "$645-675"] # New column with the bin definition ...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Scores by School Size * Perform the same operations as above, based on school size.
# Use school_summary_unformatted dataframe that still has numeric columns as float # Define the cut parameters series_to_cut = school_summary_unformatted["Total Students"] bins_to_fill = [0, 1799.9, 2999.9, 4999.9] bin_labels = ["Small (< 1800)", "Medium (1800-2999)", "Large (3000-5000)"] # New column with the bin def...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
Scores by School Type * Perform the same operations as above, based on school type
# No cut action needed since 'School Type' is not numeric. Can be grouped as is. # Exclude unneeded columns, group by School Type and take the average of the scores scores_by_school_type = (school_summary_unformatted.groupby(by="School Type") .mean() ...
_____no_output_____
Apache-2.0
PyCitySchools/PyCitySchools_1.ipynb
githotirado/pandas-challenge
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); BSSN Time-Evolution C Code Generation Library Author: Zach Etienne This module implements a number of helper functions for generating C-code kernels that solve Einstein's ...
# RULES FOR ADDING FUNCTIONS TO THIS ROUTINE: # 1. The function must be runnable from a multiprocessing environment, # which means that the function # 1.a: cannot depend on previous function calls. # 1.b: cannot create directories (this is not multiproc friendly) # Step P1: Import needed NRPy+ core modules: from o...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 2: Helper Python functions for C code generation \[Back to [top](toc)\]$$\label{helperfuncs}$$* `print_msg_with_timing()` gives the user an idea of what's going on/taking so long. Also outputs timing info.* `get_loopopts()` sets up options for NRPy+'s `loop` module* `register_stress_energy_source_terms_return_T4U...
############################################### # Helper Python functions for C code generation # print_msg_with_timing() gives the user an idea of what's going on/taking so long. Also outputs timing info. def print_msg_with_timing(desc, msg="Symbolic", startstop="start", starttime=0.0): CoordSystem = par.parval_fr...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 3.a: Generate symbolic BSSN RHS expressions \[Back to [top](toc)\]$$\label{bssnrhs}$$First we generate the symbolic expressions. Be sure to call this function from within a `reference_metric::enable_rfm_precompute="True"` environment if reference metric precomputation is desired.`BSSN_RHSs__generate_symbolic_expr...
def BSSN_RHSs__generate_symbolic_expressions(LapseCondition="OnePlusLog", ShiftCondition="GammaDriving2ndOrder_Covariant", enable_KreissOliger_dissipation=True, enable_stress_energy_sou...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 3.b: `rhs_eval()`: Register C code for BSSN RHS expressions \[Back to [top](toc)\]$$\label{bssnrhs_c_code}$$`add_rhs_eval_to_Cfunction_dict()` supports the following features* (enabled by default) reference-metric precomputation* (disabled by default) "golden kernels", which greatly increases the C-code generatio...
def add_rhs_eval_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), enable_rfm_precompute=True, enable_golden_kernels=False, enable_SIMD=True, enable_split_for_optimizations_doesnt_help=False, L...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 3.c: Generate symbolic expressions for 3-Ricci tensor $\bar{R}_{ij}$ \[Back to [top](toc)\]$$\label{ricci}$$As described above, we find a roughly 10% speedup by computing the 3-Ricci tensor $\bar{R}_{ij}$ separately from the BSSN RHS equations and storing the 6 independent components in memory. Here we construct ...
def Ricci__generate_symbolic_expressions(): ###################################### # START: GENERATE SYMBOLIC EXPRESSIONS starttime = print_msg_with_timing("3-Ricci tensor", msg="Symbolic", startstop="start") # Evaluate 3-Ricci tensor: import BSSN.BSSN_quantities as Bq par.set_parval_from_str("...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 3.d: `Ricci_eval()`: Register C function for evaluating 3-Ricci tensor $\bar{R}_{ij}$ \[Back to [top](toc)\]$$\label{ricci_c_code}$$`add_Ricci_eval_to_Cfunction_dict()` supports the following features* (enabled by default) reference-metric precomputation* (disabled by default) "golden kernels", which greatly incr...
def add_Ricci_eval_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), enable_rfm_precompute=True, enable_golden_kernels=False, enable_SIMD=True, enable_split_for_optimizations_doesnt_help=False, OMP_pragma_on="i2", ...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 4.a: Generate symbolic expressions for BSSN Hamiltonian & momentum constraints \[Back to [top](toc)\]$$\label{bssnconstraints}$$Next output the C code for evaluating the BSSN Hamiltonian and momentum constraints [(**Tutorial**)](Tutorial-BSSN_constraints.ipynb). In the absence of numerical error, these constraint...
def BSSN_constraints__generate_symbolic_expressions(enable_stress_energy_source_terms=False, leave_Ricci_symbolic=True, output_H_only=False): ###################################### # START: GENERATE SYMBOLIC EXPRESSIONS starttime = print_msg_with_timing("B...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 4.b: `BSSN_constraints()`: Register C function for evaluating BSSN Hamiltonian & momentum constraints \[Back to [top](toc)\]$$\label{bssnconstraints_c_code}$$`add_BSSN_constraints_to_Cfunction_dict()` supports the following features* (enabled by default) reference-metric precomputation* (disabled by default) "gol...
def add_BSSN_constraints_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), enable_rfm_precompute=True, enable_golden_kernels=False, enable_SIMD=True, enable_stress_energy_source_terms=False, leave_Ricci_symbolic=...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 5: `enforce_detgammahat_constraint()`: Register C function for enforcing the conformal 3-metric $\det{\bar{\gamma}_{ij}}=\det{\hat{\gamma}_{ij}}$ constraint \[Back to [top](toc)\]$$\label{enforce3metric}$$To ensure stability when solving the BSSN equations, we must enforce the conformal 3-metric $\det{\bar{\gamma...
def add_enforce_detgammahat_constraint_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), enable_rfm_precompute=True, enable_golden_kernels=False, OMP_pragma_on="i2", func_name_suffix="...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 6.a: `psi4_part_{0,1,2}()`: Register C function for evaluating Weyl scalar $\psi_4$, in 3 parts (3 functions) \[Back to [top](toc)\]$$\label{psi4}$$$\psi_4$ is a complex scalar related to the gravitational wave strain via$$\psi_4 = \ddot{h}_+ - i \ddot{h}_\times.$$We construct the symbolic expression for $\psi_4$...
def add_psi4_part_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), whichpart=0, setPsi4tozero=False, OMP_pragma_on="i2"): starttime = print_msg_with_timing("psi4, part " + str(whichpart), msg="Ccodegen", startstop="start") # Set up the C function for p...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 6.b: `psi4_tetrad()`: Register C function for evaluating Weyl scalar $\psi_4$ tetrad \[Back to [top](toc)\]$$\label{psi4_tetrad}$$Computing $\psi_4$ requires that an observer tetrad be specified. We adopt a "quasi-Kinnersley tetrad" as described in [the corresponding NRPy+ tutorial notebook](Tutorial-Psi4_tetrads...
def add_psi4_tetrad_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), setPsi4tozero=False): starttime = print_msg_with_timing("psi4 tetrads", msg="Ccodegen", startstop="start") # Set up the C function for BSSN basis transformations desc = "Compute tetrad for psi4" name = "psi4_tet...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 6.c: `SpinWeight_minus2_SphHarmonics()`: Register C function for evaluating spin-weight $s=-2$ spherical harmonics \[Back to [top](toc)\]$$\label{swm2}$$After evaluating $\psi_4$ at all interior gridpoints on a numerical grid, we next decompose $\psi_4$ into spin-weight $s=-2$ spherical harmonics, which are docum...
def add_SpinWeight_minus2_SphHarmonics_to_Cfunction_dict(includes=None, rel_path_to_Cparams=os.path.join("."), maximum_l=8): starttime = print_msg_with_timing("Spin-weight s=-2 Spherical Harmonics", msg="Ccodegen", startstop="start") # Set up the C funct...
_____no_output_____
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 7: Confirm above functions are bytecode-identical to those in `BSSN/BSSN_Ccodegen_library.py` \[Back to [top](toc)\]$$\label{validation}$$
import BSSN.BSSN_Ccodegen_library as BCL import sys funclist = [("print_msg_with_timing", print_msg_with_timing, BCL.print_msg_with_timing), ("get_loopopts", get_loopopts, BCL.get_loopopts), ("register_stress_energy_source_terms_return_T4UU", register_stress_energy_source_terms_return_T4UU, BCL...
PASS! ALL FUNCTIONS ARE IDENTICAL
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Step 8: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct...
import cmdline_helper as cmd # NRPy+: Multi-platform Python command-line interface cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-BSSN_time_evolution-C_codegen_library")
Created Tutorial-BSSN_time_evolution-C_codegen_library.tex, and compiled LaTeX file to PDF file Tutorial-BSSN_time_evolution- C_codegen_library.pdf
BSD-2-Clause
Tutorial-BSSN_time_evolution-C_codegen_library.ipynb
stevenrbrandt/nrpytutorial
Here we shall import some data taken from HiROS and import into a pandas dataframe for analysis.
# Import required data broomhall = '../data/broomhall2009.txt' davies = '../data/davies2014.txt' file = input("Please select file: 'broomhall' or 'davies': ") if file == str('broomhall'): file = broomhall elif file == str('davies'): file = davies else: print('Please try again') df = pd.read_csv(file, head...
Please select file: 'broomhall' or 'davies': broomhall
MIT
Dan_notebooks/bisondata.ipynb
daw538/y4project
We can see from the preview above that the file contains a mix of radial modes at increasing orders. To perform any useful analysis, the induvidual modes $l$ must be considered separately. A neat way of doing this is to use a list comprehension, which avoids the need for multiple for loops and appending to arrays each ...
l = [df[(df.l == i)] for i in (range(max(df.l)-min(df.l)+1))] plt.figure(1) plt.errorbar(l[0].n, l[0].nu, yerr=l[0].sg_nu, fmt='x') plt.errorbar(l[1].n, l[1].nu, yerr=l[1].sg_nu, fmt='x') plt.errorbar(l[2].n, l[2].nu, yerr=l[2].sg_nu, fmt='x') plt.errorbar(l[3].n, l[3].nu, yerr=l[3].sg_nu, fmt='x') plt.xlabel('Value of...
_____no_output_____
MIT
Dan_notebooks/bisondata.ipynb
daw538/y4project
The above Échelle diagrams show how the four lowest modes form broadly straight lines in modulo frequency space, though there are significant deviations that form a tail at the lower values of $n$ (visible as faint circles). We shall select only the $l=0$ modes for analysis. Using Vrard PaperTo compute the local frequ...
nmax = 22 # Modelling from Vrard Paper l0 = df.loc[(df.l == 0) & (df.n > 14)] l0['dnu_n'] = (l0['nu'].diff(2).shift(-1))/2 # Differences between neighbouring frequencies alpha = 0.015*np.mean(l0['dnu_n'])**(-0.32) # Equation provided in paper l0['dnu_up'] = (1 + alpha*(l0['n']-nmax)) * (np.mean(l0['dnu_n'])) ...
/usr/lib/python3.7/site-packages/ipykernel_launcher.py:5: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-ver...
MIT
Dan_notebooks/bisondata.ipynb
daw538/y4project
In order to provide Stan with suitable starting parameters (to prevent the complete lack of convergance), we shall first attempt to manually fit a rather basic model to the data.$ \Delta\nu(n+\epsilon) + k(\frac{\nu_\textrm{max}}{\Delta\nu}+n)^2 + A\sin(\omega n+\phi)e^{-(n/\tau)}$where the latter terms represent the c...
# Look at l=0 data initially only plt.figure(3, figsize=(7,4)) plt.scatter(l0.nu % dnu, l0.nu, c=l0.n,cmap='viridis', label=r'$l=$'+str(0)) plt.colorbar(label=r'Value of $n$') def model(n, dnu, nmax, epsilon, k, A, omega, phi, tau): freqs = (n + epsilon) * dnu freqs += (nmax-n)**2 * k ...
_____no_output_____
MIT
Dan_notebooks/bisondata.ipynb
daw538/y4project
Models with Multiple Source Populations *ARES* can handle an arbitrary number of source populations. Toaccess this functionality, create a dictionary representing each sourcepopulation of interest. Below, we'll create a population representative of PopII stars and another representative of PopIII stars.Before we start...
%pylab inline import ares import numpy as np import matplotlib.pyplot as pl pars = \ { 'problem_type': 100, # Blank slate global 21-cm signal # Setup star formation 'pop_Tmin{0}': 1e4, # atomic cooling halos 'pop_fstar{0}': 1e-1, # 10% star formation efficiency # Setup UV...
_____no_output_____
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
**NOTE:** See [problem_types](../problem_types.html) for more information about why we chose ``problem_type=100`` here. We might as well go ahead and run this to establish a baseline:
sim = ares.simulations.Global21cm(**pars) sim.run() ax, zax = sim.GlobalSignature(color='k')
# Loaded $ARES/input/inits/inits_planck_TTTEEE_lowl_lowE_best.txt. ############################################################################################################## #### ARES Simulation: Overview #### ##############################...
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
Now, let's add a PopIII-like source population. We'll assume that PopIII sources are brighter on average (in both the UV and X-ray) but live in lower mass halos. We could just copy-pase the dictionary above, change the population ID numbers and, for example, the UV and X-ray ``pop_rad_yield`` parameters. Or, we could u...
popII = ares.util.ParameterBundle(**pars)
_____no_output_____
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
This let's us easily extract parameters according to their ID number, and assign new ones
popIII_uv = popII.pars_by_pop(0, True) popIII_uv.num = 2 popIII_xr = popII.pars_by_pop(1, True) popIII_xr.num = 3
_____no_output_____
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
The second argument tells *ARES* to remove the parameter ID numbers.Now, we can simply reset the ID numbers and update a few important parameters:
popIII_uv['pop_Tmin{2}'] = 300 popIII_uv['pop_Tmax{2}'] = 1e4 popIII_uv['pop_temperature{2}'] = 1e5 popIII_uv['pop_fstar{2}'] = 1e-4 popIII_xr['pop_sfr_model{3}'] = 'link:sfrd:2' popIII_xr['pop_rad_yield{3}'] = 2.6e39
_____no_output_____
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
Now, let's make the final parameter dictionary and run it:
pars.update(popIII_uv) pars.update(popIII_xr) sim2 = ares.simulations.Global21cm(**pars) sim2.run() ax, zax = sim.GlobalSignature(color='k') ax, zax = sim2.GlobalSignature(color='b', ax=ax)
# Loaded $ARES/input/inits/inits_planck_TTTEEE_lowl_lowE_best.txt. ############################################################################################################## #### ARES Simulation: Overview #### ##############################...
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
Note that the parameter file hangs onto the parameters of each population separately. To verify a few key changes, you could do:
len(sim2.pf.pfs) for key in ['pop_Tmin', 'pop_fstar', 'pop_rad_yield']: print(key, sim2.pf.pfs[0][key], sim2.pf.pfs[2][key])
pop_Tmin 10000.0 300 pop_fstar 0.1 0.0001 pop_rad_yield 1e+42 1e+42
MIT
docs/examples/example_gs_multipop.ipynb
mirochaj/ares
*This notebook contains material from [PyRosetta](https://RosettaCommons.github.io/PyRosetta.notebooks);content is available [on Github](https://github.com/RosettaCommons/PyRosetta.notebooks.git).* Refinement ProtocolThe entire standard Rosetta refinement protocol, similar to that presented in Bradley, Misura, & Bake...
# Notebook setup import sys if 'google.colab' in sys.modules: !pip install pyrosettacolabsetup import pyrosettacolabsetup pyrosettacolabsetup.setup() print ("Notebook is set for PyRosetta use in Colab. Have fun!") from pyrosetta import * from pyrosetta.teaching import * init()
core.init: Checking for fconfig files in pwd and ./rosetta/flags core.init: Rosetta version: PyRosetta4.Release.python36.mac r208 2019.04+release.fd666910a5e fd666910a5edac957383b32b3b4c9d10020f34c1 http://www.pyrosetta.org 2019-01-22T15:55:37 core.init: command: PyRosetta -ex1 -ex2aro -database...
MIT
notebooks/05.02-Refinement-Protocol.ipynb
So-AI-love/PyRosetta.notebooks
**Make sure you are in the directory with the pdb files:**`cd google_drive/My\ Drive/student-notebooks/`
### BEGIN SOLUTION sfxn = get_score_function() pose = pose_from_pdb("inputs/1YY8.clean.pdb") relax = pyrosetta.rosetta.protocols.relax.FastRelax() relax.set_scorefxn(sfxn) #Skip for tests if not os.getenv("DEBUG"): relax.apply(pose) ### END SOLUTION
core.scoring.ScoreFunctionFactory: SCOREFUNCTION: ref2015 core.scoring.etable: Starting energy table calculation core.scoring.etable: smooth_etable: changing atr/rep split to bottom of energy well core.scoring.etable: smooth_etable: spline smoothing lj etables (maxdis = 6) c...
MIT
notebooks/05.02-Refinement-Protocol.ipynb
So-AI-love/PyRosetta.notebooks
Tutorial - Translation> Using the Translation API in AdaptNLP TranslationTranslation is the task of producing the input text in another language.Below, we'll walk through how we can use AdaptNLP's `EasyTranslator` module to translate text with state-of-the-art models. Getting StartedWe'll first import the `EasyTrans...
from adaptnlp import EasyTranslator
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
Then we'll write some example text to use:
text = ["Machine learning will take over the world very soon.", "Machines can speak in many languages.",]
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
Followed by instantiating the `EasyTranslator` class:
translator = EasyTranslator()
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
Next we can translate our text. We pass in the text we wish to translate, optionally a prefix for the t5 model (only used with t5 models), a model name, and any keyword arguments from `Transformers.PreTrainedModel.generate()`.Here we'll pass in `text`, have our model translate from English to German, and use the `t5-sm...
translations = translator.translate(text = text, t5_prefix="translate English to German", model_name_or_path="t5-small", mini_batch_size=1, min_length=0, max_length=100, early_stopping=True)
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
And we can look at the outputs:
print("Translations:\n") for t in translations: print(t, "\n")
Translations: Das Maschinenlernen wird die Welt in Kürze übernehmen. Maschinen können in vielen Sprachen sprechen.
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
Finding a Model with the Model Hub Using the `HFModelHub` we can search for any translation models in HuggingFace like so:
from adaptnlp import HFModelHub hub = HFModelHub() models = hub.search_model_by_task('translation'); models
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
From there we can pass in any `HFModelResult` from it. Here we'll use the `t5-small` again:
model = models[-1] translations = translator.translate(text = text, t5_prefix="translate English to German", model_name_or_path=model, mini_batch_size=1, min_length=0, max_length=100, early_stopping=True)
_____no_output_____
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
And see that we get similar results:
print("Translations:\n") for t in translations: print(t, "\n")
Translations: Das Maschinenlernen wird die Welt in Kürze übernehmen. Maschinen können in vielen Sprachen sprechen.
Apache-2.0
nbs/08a_tutorial.translation.ipynb
chsafouane/adaptnlp
NO2 Prediction by using Machine Learning Regression Analyses in Google Earth Engine **Machine Learning can create a Model to Predict specific value base on existing data set (dependent and independent values).** **Introduction** **Nitrogen Dioxide (NO2) air pollution**.The World Health Organization estimates that ai...
_____no_output_____
BSD-3-Clause
scripts_modules/CoLab_Random_Forest_Regression.ipynb
annapav7/NO2-tropomi_prediction_analysis
**DataSet:**The Sentinel-5P satellite with TROPOspheric Monitoring Instrument (TROPOMI) instrument provides high spectral resolution (7x3.5 km2) for all spectral bands to register level of NO2. TROPOMI available from October 13, 2017.Landsat satellite launched in 1972 and images are available for more then 40 years. ...
!pip install earthengine-api
_____no_output_____
BSD-3-Clause
scripts_modules/CoLab_Random_Forest_Regression.ipynb
annapav7/NO2-tropomi_prediction_analysis
2._ Establish connection
!earthengine authenticate
_____no_output_____
BSD-3-Clause
scripts_modules/CoLab_Random_Forest_Regression.ipynb
annapav7/NO2-tropomi_prediction_analysis
**`Complete End to End Python code for Random Forest Regression:`**
# Import necessary Libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import rasterio as rio from rasterio.plot import show # Import the data ( CSV formats) data = pd.read_csv('name_of_file.csv') data.head() # Store the Data in form of dependent and independent variables separatly X = dat...
_____no_output_____
BSD-3-Clause
scripts_modules/CoLab_Random_Forest_Regression.ipynb
annapav7/NO2-tropomi_prediction_analysis
**Model Evaluation**
#Model Evaluation using Mean Square Error (MSE) print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_predict)) #Model Evaluation using Root Mean Square Error (RMSE) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_predict))) #Model Evaluation using Mean Absolute Error (MAE) pr...
_____no_output_____
BSD-3-Clause
scripts_modules/CoLab_Random_Forest_Regression.ipynb
annapav7/NO2-tropomi_prediction_analysis
Widgets without writing widgets: interact The `interact` function (`ipywidgets.interact`) automatically creates user interface (UI) controls for exploring code and data interactively. It is the easiest way to get started using IPython's widgets.
from ipywidgets import interact, interactive, fixed, interact_manual import ipywidgets as widgets
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Basic `interact` At the most basic level, `interact` autogenerates UI controls for function arguments, and then calls the function with those arguments when you manipulate the controls interactively. To use `interact`, you need to define a function that you want to explore. Here is a function that triples its argument...
def f(x): return 3 * x
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
When you pass this function as the first argument to `interact` along with an integer keyword argument (`x=10`), a slider is generated and bound to the function parameter.
interact(f, x=10);
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
When you move the slider, the function is called, and the return value is printed.If you pass `True` or `False`, `interact` will generate a checkbox:
interact(f, x=True);
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
If you pass a string, `interact` will generate a `Text` field.
interact(f, x='Hi there!');
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
`interact` can also be used as a decorator. This allows you to define a function and interact with it in a single shot. As this example shows, `interact` also works with functions that have multiple arguments.
@widgets.interact(x=True, y=1.0) def g(x, y): return (x, y)
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Fixing arguments using `fixed` There are times when you may want to explore a function using `interact`, but fix one or more of its arguments to specific values. This can be accomplished by wrapping values with the `fixed` function.
def h(p, q): return (p, q)
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
When we call `interact`, we pass `fixed(20)` for q to hold it fixed at a value of `20`.
interact(h, p=5, q=fixed(20));
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Notice that a slider is only produced for `p` as the value of `q` is fixed. Widget abbreviations When you pass an integer-valued keyword argument of `10` (`x=10`) to `interact`, it generates an integer-valued slider control with a range of `[-10, +3*10]`. In this case, `10` is an *abbreviation* for an actual slider wi...
interact(f, x=widgets.IntSlider(min=-10, max=30, step=1, value=10));
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
This examples clarifies how `interact` processes its keyword arguments:1. If the keyword argument is a `Widget` instance with a `value` attribute, that widget is used. Any widget with a `value` attribute can be used, even custom ones.2. Otherwise, the value is treated as a *widget abbreviation* that is converted to a w...
interact(f, x=(0, 4));
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
A `FloatSlider` is generated if any of the values are floating point. The step size can be changed by passing a third element in the tuple.
interact(f, x=(0, 10, 0.01));
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Exercise: Reverse some textHere is a function that takes text as an input and returns the text backwards.
def reverse(x): return x[::-1] reverse('I am printed backwards.')
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Use `interact` to make interactive controls for this function.
# %load solutions/interact-basic-list/reverse-text.py
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
For both integer and float-valued sliders, you can pick the initial value of the widget by passing a default keyword argument to the underlying Python function. Here we set the initial value of a float slider to `5.5`.
@interact(x=(0.0, 20.0, 0.5)) def h(x=5.5): return x
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Dropdown menus are constructed by passing a list of strings. In this case, the strings are both used as the names in the dropdown menu UI and passed to the underlying Python function.
interact(f, x=['apples','oranges']);
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
If you want a dropdown menu that passes non-string values to the Python function, you can pass a list of tuples of the form `('label', value)`. The first items are the names in the dropdown menu UI and the second items are values that are the arguments passed to the underlying Python function.
interact(f, x=[('one', 10), ('two', 20)]);
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Basic interactive plotThough the examples so far in this notebook had very basic output, more interesting possibilities are straightforward. The function below plots a straight line whose slope and intercept are given by its arguments.
%matplotlib widget import matplotlib.pyplot as plt import numpy as np def f(m, b): plt.figure(2) plt.clf() plt.grid() x = np.linspace(-10, 10, num=1000) plt.plot(x, m * x + b) plt.ylim(-5, 5) plt.show()
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
The interactive below displays a line whose slope and intercept is set by the sliders. Note that if the variable containing the widget, `interactive_plot`, is the last thing in the cell it is displayed.
interact(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Exercise: Make a plotHere is a python function that, given $k$ and $p$, plots $f(x) = \sin(k x - p)$.
def plot_f(k, p): plt.figure(5) plt.clf() plt.grid() x = np.linspace(0, 4 * np.pi) y = np.sin(k*x - p) plt.plot(x, y) plt.show()
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
Copy the above function definition and make it interactive using `interact`, so that there are sliders for the parameters $k$ and $p$, where $0.5\leq k \leq 2$ and $0 \leq p \leq 2\pi$ (hint: use `np.pi` for $\pi$).
# %load solutions/interact-basic-list/plot-function.py
_____no_output_____
BSD-3-Clause
notebooks/02.Interact/02.00-Using-Interact.ipynb
ibdafna/tutorial
We want to analyze participants and patterns of participation across IETF groups. How many people participate, in which groups, how does affiliation, gender, RFC authorship or other characteristics relate to levels of participation, and a variety of other related questions. How do groups relate to one another? Which pa...
%matplotlib inline import bigbang.ingress.mailman as mailman import bigbang.analysis.graph as graph import bigbang.analysis.process as process from bigbang.parse import get_date from bigbang.archive import Archive import bigbang.utils as utils import pandas as pd import datetime import matplotlib.pyplot as plt import n...
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Let's start with a single IETF mailing list. (Later, we can expand to all current groups, or all IETF lists ever.)
list_url = '6lo' # perpass happens to be one that I subscribe to ietf_archives_dir = '../archives' # relative location of the ietf-archives directory/repo list_archive = mailman.open_list_archives(list_url, ietf_archives_dir) activity = Archive(list_archive).get_activity() people = None people = pd.DataFrame(activity...
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Now repeat, parsing the archives and collecting the activities for all the mailing lists in the corpus. To make this faster, we try to open pre-created `-activity.csv` files which contain the activity summary for the full list archive. These files are created with `bin/mail_to_activity.py` or might be included in the m...
f = open('../examples/mm.ietf.org.txt', 'r') ietf_lists = set(f.readlines()) # remove duplicates, which is a bug in list maintenance list_activities = [] for list_url in ietf_lists: try: activity_summary = mailman.open_activity_summary(list_url, ietf_archives_dir) if activity_summary is not None: ...
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Merge all of the activity summaries together, so that every row is a "From" field, with a column for every mailing list and a cell that includes the number of messages sent to that list. This will be a very sparse, 2-d table. **This operation is a little slow.** Don't repeat this operation without recreating `people` f...
list_columns = [] for (list_url, activity_summary) in list_activities: list_name = mailman.get_list_name(list_url) activity_summary.rename(columns={'Message Count': list_name}, inplace=True) # name the message count column for the list people = pd.merge(people, activity_summary, how='outer', left_index=True...
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Split out the email address and header name from the From header we started with.
froms = pd.Series(people.index) emails = froms.apply(lambda x: email.utils.parseaddr(x)[1]) emails.index = people.index names = froms.apply(lambda x: email.utils.parseaddr(x)[0]) names.index = people.index people['email'] = emails people['name'] = names
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Let's create some summary statistical columns.
people['Total Messages'] = people[list_columns].sum(axis=1) people['Number of Groups'] = people[list_columns].count(axis=1) people['Median Messages per Group'] = people[list_columns].median(axis=1) people['Total Messages'].sum()
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
In this corpus, **101,510** "people" sent a combined total of **1.2 million messages**. Most people sent only 1 message. Participation patterns The vast majority of people send only a few messages, and to only a couple of lists. (These histograms use a log axis for Y, without which you couldn't even see the columns be...
people[['Total Messages']].plot(kind='hist', bins=100, logy=True, logx=False) people[['Number of Groups']].plot(kind='hist', bins=100, logy=True, logx=False)
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
Let's limit our analysis for now to people who have sent at least 5 messages. We will also create log base 10 versions of our summary columns for easier graphing later.
working = people[people['Total Messages'] > 5] working['Total Messages (log)'] = np.log10(working['Total Messages']) working['Number of Groups (log)'] = np.log10(working['Number of Groups'])
/home/lem/.local/lib/python2.7/site-packages/ipykernel_launcher.py:3: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#index...
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang
The median number of messages that a user sends to a group is also heavily weighted towards a small number, but the curve doesn't seem to drop off in the same extreme manner. There is a non-random tendency to send some messages to a group?
working[['Median Messages per Group']].plot(kind='hist', bins=100, logy=True)
_____no_output_____
MIT
examples/experimental_notebooks/IETF Participants.ipynb
nllz/bigbang