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 |
|---|---|---|---|---|---|
ASSIGNMENT 1) Replicate the lesson code. I recommend that you [do not copy-paste](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit).Get caught up to where we got our example in class and then try and take things further. How close to "pixel perfect" can you make the lecture graph?O... | # Your Work Here
from IPython.display import display, Image
url = 'https://fivethirtyeight.com/wp-content/uploads/2017/09/mehtahickey-inconvenient-0830-1.png'
example = Image(url=url, width=400)
display (example)
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as num
import pandas as pd
plt.style.... | _____no_output_____ | MIT | Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling-OLD |
STRETCH OPTIONS 1) Reproduce one of the following using the matplotlib or seaborn libraries:- [thanksgiving-2015](https://fivethirtyeight.com/features/heres-what-your-part-of-america-eats-on-thanksgiving/) - [candy-power-ranking](https://fivethirtyeight.com/features/the-ultimate-halloween-candy-power-ranking/) - or an... | # More Work Here | _____no_output_____ | MIT | Sam_Kumar_LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | sampath11/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling-OLD |
Basic Operations on Images | Drawing on Images
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import cv2 | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
Create a black image which will act as a template. | image_blank = np.zeros(shape=(512,512,3),dtype=np.int16) | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
image_blank Display the black image. | plt.imshow(image_blank) | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
Function & Attributes The generalised function for drawing shapes on images is: cv2.shape(line, rectangle etc)(image,Pt1,Pt2,color,thickness) There are some common arguments which are passed in function to draw shapes on images:* Image on which shapes are to be drawn* co-ordinates of the shape to be drawn from Pt1(top... | # Draw a diagonal red line with thickness of 5 px
line_red = cv2.line(image_blank,(0,0),(500,500),(255,0,255),10)
plt.imshow(line_red)
# Draw a diagonal green line with thickness of 5 px
line_green = cv2.line(image_blank,(0,0),(511,511),(0,255,0),5)
plt.imshow(line_green)
# Draw a diagonal green line with thickness of ... | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
2. Rectangle For a rectangle, we need to specify the top left and the bottom right coordinates. | #Draw a blue rectangle with a thickness of 5 px
rectangle= cv2.rectangle(image_blank,(0,0),(510,128),(0,255,0),25)
plt.imshow(rectangle) | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
3. Circle | For a circle, we need to pass its center coordinates and radius value. Let us draw a circle inside the rectangle drawn above
img1 = cv2.circle(image_blank,(447,0), 250, (255,0,0), 50) # -1 corresponds to a filled circle
plt.imshow(img1) | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
Writing on Images Adding text to images is also similar to drawing shapes on them. But you need to specify certain arguments before doing so:* Text to be written* coordinates of the text. The text on an image begins from the bottom left direction.* Font type and scale.* Other attributes like color, thickness and line t... | font = cv2.FONT_HERSHEY_SIMPLEX
text = cv2.putText(img1,'Alok',(10,500), font, 4,(255,255,255),2)
plt.imshow(text)
These were the minor operations that can be done on images using OpenCV. Feel free to experiment with the shapes and text. | _____no_output_____ | MIT | 8.Open CV/Basics of open cv.ipynb | Jiggu07/FACE-MASK-RECOGNITION |
- Install the Colab Code package which will let you run jupyter lab in colab using ngrok tunnel | !pip install colabcode | Collecting colabcode
Downloading https://files.pythonhosted.org/packages/5d/d5/4f9db2a4fe80f507c9c44c2cd4fd614234c1fe0d77e8f1101329997a19cd/colabcode-0.0.9-py3-none-any.whl
Collecting pyngrok>=5.0.0
Downloading https://files.pythonhosted.org/packages/ea/63/e086f165125e9bf2e71c0db2955911baaaa0af8947ab5c7b3771bdf4d4d... | MIT | Jupyter_Lab_Colab.ipynb | debparth/Colab_tips_tricks |
- Paste your **Authorization Code** below in **authtoken** after signing up from [**here**](https://dashboard.ngrok.com/signup) - Click on the **XXXXXXXXX.ngrok.io** link below after running the cell | from colabcode import ColabCode
ColabCode(authtoken="", mount_drive=True, lab=True) | Code Server can be accessed on: NgrokTunnel: "http://9998767f9579.ngrok.io" -> "http://localhost:10000"
[2020-10-28T19:04:23.315Z] info Using user-data-dir ~/.local/share/code-server
[2020-10-28T19:04:23.321Z] info code-server 3.6.1 62735da69466a444561ab9b1115dc7c4d496d455
[2020-10-28T19:04:23.322Z] info Using confi... | MIT | Jupyter_Lab_Colab.ipynb | debparth/Colab_tips_tricks |
--- Day 3: Binary Diagnostic --- [](https://mybinder.org/v2/gh/oddrationale/AdventOfCode2021FSharp/main?urlpath=lab%2Ftree%2FDay03.ipynb) The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case.The diagnostic report ... | let input = File.ReadAllLines @"input/03.txt"
#!time
input
|> Seq.map (fun line -> line.ToCharArray() |> Seq.map (fun char -> char |> string |> int))
|> Seq.transpose
|> Seq.map (fun bits -> if (bits |> Seq.sum) * 2 > input.Length then (1, 0) else (0, 1))
|> Seq.fold (fun (gamma, epsilon) (g, e) -> gamma + string g, ep... | _____no_output_____ | MIT | Day03.ipynb | oddrationale/AdventOfCode2021FSharp |
--- Part Two --- Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating.Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both valu... | let mostCommonBit bits =
match (bits |> Seq.sum) with
| sum when sum * 2 >= (bits |> Seq.length) -> 1
| _ -> 0
let leastCommonBit bits =
match (bits |> Seq.sum) with
| sum when sum * 2 >= (bits |> Seq.length) -> 0
| _ -> 1
let filter bitCriteria pos (input: seq<string>) =
let column =
... | _____no_output_____ | MIT | Day03.ipynb | oddrationale/AdventOfCode2021FSharp |
Getting Predictions and Prediction Explanations**Author**: Thodoris Petropoulos**Label**: Model Deployment ScopeThe scope of this notebook is to provide instructions on how to get predictions and prediction explanations out of a trained model using the Python API. BackgroundThe main ways you can get predictions out of... | import datarobot as dr | _____no_output_____ | Apache-2.0 | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists |
Requesting PredictionsBefore actually requesting predictions, you should upload the dataset you wish to predict via Project.upload_dataset. Previously uploaded datasets can be seen under Project.get_datasets. When uploading the dataset you can provide the path to a local file, a file object, raw file content, a pandas... | #Uploading prediction dataset
dataset_from_path = project.upload_dataset('path/file')
#Request predictions
predict_job = model.request_predictions(dataset_from_path.id)
#Waiting for prediction calculations
predictions = predict_job.get_result_when_complete()
predictions.head() | _____no_output_____ | Apache-2.0 | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists |
Requesting Prediction ExplanationsIn order to create PredictionExplanations for a particular model and dataset, you must first Compute feature impact for the model via dr.Model.get_or_request_feature_impact() | model.get_or_request_feature_impact()
pei = dr.PredictionExplanationsInitialization.create(project.id, model.id)
#Wait for results of Prediction Explanations
pei.get_result_when_complete()
pe_job = dr.PredictionExplanations.create(project.id, model.id, dataset_from_path.id)
#Waiting for Job to Complete
pe = pe_job... | _____no_output_____ | Apache-2.0 | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists |
Time Series Projects CaveatsPrediction datasets are uploaded as normal predictions. However, when uploading a prediction dataset, a new parameter forecastPoint can be specified. The forecast point of a prediction dataset identifies the point in time relative which predictions should be generated, and if one is not spe... | """
Usage:
python datarobot-predict.py <input-file.csv>
This example uses the requests library which you can install with:
pip install requests
We highly recommend that you update SSL certificates with:
pip install -U urllib3[secure] certifi
"""
import sys
import json
import requests
API_URL = 'Find thi... | _____no_output_____ | Apache-2.0 | Making Predictions/Python/Getting Predictions and Prediction Explanations.ipynb | hcchengithub/examples-for-data-scientists |
Double Machine Learning: Summarized Data and InterpretabilityDouble Machine Learning (DML) is an algorithm that applies arbitrary machine learning methodsto fit the treatment and response, then uses a linear model to predict the response residualsfrom t... | %load_ext autoreload
%autoreload 2
# Helper imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
%matplotlib inline
import seaborn as sns | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Generating Raw Data | import scipy.special
np.random.seed(123)
n=10000 # number of raw samples
d=10 # number of binary features + 1
# Generating random segments aka binary features. We will use features 1,...,4 for heterogeneity.
# The rest for controls. Just as an example.
X = np.random.binomial(1, .5, size=(n, d))
# The first column of ... | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Creating Summarized DataFor each segment, we split the data in two and create one summarized copy for each split. The summarized copy contains the number of samples that were summarized and the variance of the observations for the summarized copies. Optimally we would want two copies per segment, as I'm creating here,... | from econml.tests.test_statsmodels import _summarize
X_sum = np.unique(X, axis=0)
n_sum = np.zeros(X_sum.shape[0])
# The _summarize function performs the summary operation and returns the summarized data
# For each segment we have two copies.
X1, X2, y1, y2, X1_sum, X2_sum, y1_sum, y2_sum, n1_sum, n2_sum, var1_sum, va... | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Applying the LinearDML | from econml.sklearn_extensions.linear_model import WeightedLassoCV
from econml.dml import LinearDML
from sklearn.linear_model import LogisticRegressionCV
# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly
# as long as it accepts the sample_weight keyword argument at fi... | [['A' '2.0151755553187574']
['B' '0.07589941486626034']
['C' '-0.026742049958516114']
['D' '-0.12871399676275952']]
| BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Non-Linear CATE Models with Polynomial Features | from econml.sklearn_extensions.linear_model import WeightedLassoCV
from econml.dml import LinearDML
from sklearn.linear_model import LogisticRegressionCV
from sklearn.preprocessing import PolynomialFeatures
# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly
# as long a... | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Non-Linear CATE Models with Forests | from econml.dml import CausalForestDML
from sklearn.ensemble import GradientBoostingRegressor, GradientBoostingClassifier
# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly
# as long as it accepts the sample_weight keyword argument at fit time.
est = CausalForestDML(mo... | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Tree Interpretation of the CATE Model | from econml.cate_interpreter import SingleTreeCateInterpreter
intrp = SingleTreeCateInterpreter(include_model_uncertainty=True, max_depth=2, min_samples_leaf=1)
# We interpret the CATE models behavior on the distribution of heterogeneity features
intrp.interpret(est, X_sum[:, 1:5])
# exporting to a dot file
intrp.expor... | C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
after removing the cwd from sys.path.
| BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Tree Based Treatment Policy Based on CATE Model | from econml.cate_interpreter import SingleTreePolicyInterpreter
intrp = SingleTreePolicyInterpreter(risk_level=0.05, max_depth=3, min_samples_leaf=1, min_impurity_decrease=.001)
# We find a tree based treatment policy based on the CATE model
# sample_treatment_costs is the cost of treatment. Policy will treat if effect... | C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:4: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure.
after removing the cwd from sys.path.
| BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Appendix: AmendmentTo make estimation even more precise one should simply choose the two splits used during the crossfit part of Double Machine Learning so that each summaried copy of a segment ends up in a separate split. We can do this as follows: | from econml.sklearn_extensions.linear_model import WeightedLassoCV
from econml.dml import LinearDML
from sklearn.linear_model import LogisticRegressionCV
# One can replace model_y and model_t with any scikit-learn regressor and classifier correspondingly
# as long as it accepts the sample_weight keyword argument at fi... | _____no_output_____ | BSD-3-Clause | notebooks/Weighted Double Machine Learning Examples.ipynb | lwschm/EconML |
Working with remote analysis Columns in remote dataset:ClassificationYearPeriodPeriod Desc.Aggregate LevelIs Leaf CodeTrade Flow CodeTrade FlowReporter CodeReporterReporter ISOPartner CodePartnerPartner ISOCommodity CodeCommodityQty Unit CodeQty UnitQtyNetweight (kg)Trade Value (US$)Flag | # Our request was denied, we will get an error
private_dataset_ptr.get()
total_sum = 0
for row in private_dataset_ptr:
if row[6] == 1: # Trade Flow Code 1 == Import
print("This row was imported")
total_sum += row[-2]
print(f'The total value of all Canadian Imports in this dataset amounts to USD${to... | <syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13de11160>
<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x10454d5e0>
<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13ddeb5b0>
<syft.proxy.syft.core.tensor.tensor.TensorPointer object at 0x13e3ca670>
<syft.proxy.syft.core.tensor... | Apache-2.0 | notebooks/Experimental/Ishan/ADP Demo/Old Versions/Final Demo DataScientist.ipynb | Noob-can-Compile/PySyft |
Distribution of publication count for Dmel TF genesFor each TF gene, count the number of *curated* publications, using data from GO and Monarch | import ontobio.golr.golr_associations as ga
# Fetch all Dmel TF genes
DNA_BINDING_TF = 'GO:0003700'
DMEL = 'NCBITaxon:7227'
tf_genes = ga.get_subjects_for_object(object=DNA_BINDING_TF, subject_taxon=DMEL)
len(tf_genes)
# Routine to go to GO and Monarch to fetch all annotations for a gene
def get_pubs_for_gene(g):
... | _____no_output_____ | BSD-3-Clause | notebooks/TF_Pub_Analysis.ipynb | alliance-genome/ontobio |
1-5.1 Python Intro conditionals, type, and mathematics extended - **conditionals: `elif`**- **casting** - basic math operators -----> Student will be able to - **code more than two choices using `elif`** - **gather numeric input using type casting** - perform subtraction, multiplication and division operations ... | # [ ] review the code then run testing different inputs
# WHAT TO WEAR
weather = input("Enter weather (sunny, rainy, snowy): ")
if weather.lower() == "sunny":
print("Wear a t-shirt")
elif weather.lower() == "rainy":
print("Bring an umbrella and boots")
elif weather.lower() == "snowy":
print("Wear a warm c... | _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Task 1 Program: Shirt Sale Complete program using `if, elif, else`- Get user input for variable size (S, M, L)- reply with each shirt size and price (Small = \$ 6, Medium = \$ 7, Large = \$ 8)- if the reply is other than S, M, L, give a message for not available- *optional*: add additional sizes | # [ ] code and test SHIRT SALE
| _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Concepts castingCasting is the conversion from one data type to another Such as converting from **`str`** to **`int`**.[]( http://edxinteractivepage.blob.core.windows.net/edxpages/f7cff1a7-5601-48a1-95a6-fd1fdfab... | weight1 = '60' # a string
weight2 = 170 # an integer
# add 2 integers
total_weight = int(weight1) + weight2
print(total_weight) | 230
| MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Task 2 casting with `int()` & `str()` | str_num_1 = "11"
str_num_2 = "15"
int_num_3 = 10
# [ ] Add the 3 numbers as integers and print the result
str_num_1 = "11"
str_num_2 = "15"
int_num_3 = 10
# [ ] Add the 3 numbers as test strings and print the result
| _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Task 2 cont... Program: adding using `int` casting- **[ ]** initialize **`str_integer`** variable to a **string containing characters of an integer** (quotes) - **[ ]** initialize **`int_number`** variable with an **integer value** (no quotes)- **[ ]** initialize **`number_total`** variable and **add int_number + st... | # [ ] code and test: adding using int casting
str_integer = "2"
int_number = 10
number_total = int(str_integer) + int_number
print(number_total)
| _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Concepts `input()` strings that represent numbers can be "cast" to integer values Example | # [ ] review and run code
student_age = input('enter student age (integer): ')
age_next_year = int(student_age) + 1
print('Next year student will be',age_next_year)
# [ ] review and run code
# cast to int at input
student_age = int(input('enter student age (integer): '))
age_in_decade = student_age + 10
print('In a d... | _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Task 3 Program: adding calculator- get input of 2 **integer** numbers - cast the input and print the input followed by the result - Output Example: **`9 + 13 = 22`** Optional: check if input .isdigit() before trying integer addition to avoid errors in casting invalid inputs | # [ ] code and test the adding calculator
| _____no_output_____ | MIT | Python Absolute Beginner/Module_3_4_Absolute_Beginner.ipynb | serah-wif/pythonteachingcode |
Read DataWe run into memory issues using the code block below:```pythondata = pd.read_json('../data/17.04_association_data.json', orient='records', typ='frame', lines=True, numpy=True)```Thus, I have turned to another library to iteratively lo... | # Convert the JSON data to a list of strings. I can then parse the strings
# using usjon later.
filename = '../data/17.04_association_data.json'
with open(filename, 'r+') as f:
data = f.readlines()
data = [x.rstrip() for x in data]
len(data)
from pprint import pprint
pprint(json.loads(data[0])) | {'association_score': {'datasources': {'cancer_gene_census': 0.90830650599492,
'chembl': 0.825695006743774,
'europepmc': 0.30565916633482804,
'eva': 0.905780555555555,
... | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
From observation, I'm seeing that the `datatypes` key-value dictionary under the `association_score` data dictionary looks like the thing that is used for data analysis. On the other hand, there's an `evidence_count` thing as well - I think that one is the so-called "raw data". What was used in the paper should be the ... | from tqdm import tqdm
records = []
for d in tqdm(data):
# Get the datatype out.
d = json.loads(d)
record = d['association_score']['datatypes']
# Add the target symbol to the record.
record['target'] = d['target']['gene_info']['symbol']
record['target_id'] = d['target']['id']
# Add the diseas... | 100%|██████████| 2673321/2673321 [00:44<00:00, 60570.96it/s]
| MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
Let's write this to the "feather" format - it'll let us load the dataframe really quickly in other notebooks. | pd.DataFrame(records).to_feather('../data/association_score_data_types.feather') | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
Just to test, let's reload the dataframe. | df = pd.read_feather('../data/association_score_data_types.feather')
df.head() | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
Great! Sanity check passed :). Exploratory AnalysisLet's go on to some exploratory analysis of the data.I'd like to first see how many of each target type is represented in the dataset.In the paper, for each target, the GSK research group used a simple "mean" of all evidence strengths across all diseases for a given ta... | df_cv = df.replace(0, 1E-6).groupby('target').std() / df.replace(0, 1E-6).groupby('target').mean()
df_cv.sample(10) | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
How many target-disease pairs represented? | len(df) | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
How many unique targets are there? | len(df_cv) | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
And how many unique diseases are represented? | len(df.groupby('disease').mean())
# Theoretical number of target-disease pairs
len(df_cv) * len(df.groupby('disease').mean()) | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
If densely populated, there should be $ 31051 \times 8891 \approx 270 million $ unique combinations. However, we only have $ 2673321 \approx 2.6 million $ target-disease pairs represented. That means a very sparse dataset. Let's now do a simple count of the cells here:- How many have non-zero values?- Of those that hav... | # This is the number of cells that have nonzero values.
df_cv[df_cv != 0].isnull()
import matplotlib.pyplot as plt
import numpy as np
def ecdf(data):
x, y = np.sort(data), np.arange(1, len(data)+1) / len(data)
return x, y | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
Let's make an ECDF scatter plot of the non-zero data. We're still only interested in the coefficient of variation (CV). In the following plots, I will plot the ECDF of log10-transformed CV scores for each target. Recall that CV 1 indicates variation greater than mean. I would like to see what proportion of CV scores a... | from matplotlib.gridspec import GridSpec
from scipy.stats import percentileofscore as pos
df_cv_nonzero = df_cv[df_cv != 0]
gs = GridSpec(2, 4)
fig = plt.figure(figsize=(12, 6))
for i, col in enumerate(df_cv.columns):
x, y = ecdf(df_cv_nonzero[col].dropna())
x = np.log10(x)
ax = fig.add_subplot(gs[i])
... | _____no_output_____ | MIT | notebooks/01-data-exploration.ipynb | ericmjl/target-prediction |
Segmentação de Clientes Nesse Notebooks, vamos fazer segmetação de Clie | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import style
import plotly
import matplotlib.dates as mdates
from datetime import datetime, timedelta
import plotly.offline as pyoff
import plotly.graph_objs as go
#initiate visualization library for jupyter n... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
Limpeza dos dados | # converting date columns to datetime
date_columns = ['shipping_limit_date', 'order_purchase_timestamp', 'order_approved_at', 'order_delivered_carrier_date', 'order_delivered_customer_date', 'order_estimated_delivery_date']
for col in date_columns:
df[col] = pd.to_datetime(df[col], format='%Y-%m-%d %H:%M:%S')
# cle... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
Análise exploratória de dados | n_customers = df['customer_unique_id'].nunique()
print('Unique customers: {}'.format(n_customers))
n_cities = df['customer_city'].nunique()
print('Unique cities: {}'.format(n_cities))
# City disctribution
df['customer_city'].value_counts().sort_values(ascending=False)
cities = df['customer_city'].value_counts().sort_va... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
**Crescimento Mensal** | #calculate Revenue for each row and create a new dataframe with YearMonth - Revenue columns
df_revenue = df.groupby(['month_year'])['payment_value'].sum().reset_index()
df_revenue
#calculating for monthly revenie growth rate
# using pct_change() function to see monthly percentage change
df_revenue['MonthlyGrowth'] = df... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
**Média de por compra de clientes** | # create a new dataframe for average revenue by taking the mean of it
df_monthly_order_avg = df.groupby('month_year')['payment_value'].mean().reset_index()
fig, ax = plt.subplots(figsize=(12, 6))
sns.set(palette='muted', color_codes=True, style='whitegrid')
bar_plot(x='month_year', y='payment_value', df=df_monthly_ord... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
Segmentação de Clientes A segmetação irá classificar clionets baseado na frequencia de compra, quantidade de comprar e dinheiro gasto.* Como os clientes são segmentados de acordo com tempo gasto na comaprar, quantidade na comprar e o número de pedidos? | df['order_status'].value_counts()
df_customer = df[df['order_status']=='delivered']
# Setting reference day
df_customer['today'] = df_customer['order_purchase_timestamp'].max()
# Date deltas
df_customer['recency'] = df_customer['today'] - df['order_purchase_timestamp'] | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/Customer-Segmentation-checkpoint.ipynb | gabedewitt/Ollist_End_to_End |
Processing of a single image Loading the HDF5 file and converting to tiff | root_hdf5 = '../../pytorch/fake_images_TI/hdf5'
root_tiff = '../../pytorch/fake_images_TI/tiff'
root_postprocess_tiff = '../../pytorch/fake_images_TI/postprocess_tiff'
files_name = os.listdir(root_hdf5)
print(files_name)
for file_name in files_name:
file_path = os.path.join(root_hdf5, file_name)
f = h5py.File(... | _____no_output_____ | MIT | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D |
Denoising and thresholding | files_name = os.listdir(root_tiff)
for file_name in files_name:
file_path = os.path.join(root_tiff, file_name)
im_in = tifffile.imread(file_path)
#apply single pixel denoising
im_in = median_filter(im_in, size=(3, 3, 3))
#cutaway outer noise area
#im_in = im_in[40:240, 40:240, 40:240]
#No... | _____no_output_____ | MIT | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D |
Compute porosity | segmented_image = tifffile.imread("postprocessed_example.tiff")
porc = Counter(segmented_image.flatten())
print(porc)
porosity = porc[0]/float(porc[0]+porc[1])
print("Porosity of the sample: ", porosity) | Counter({1: 6425472, 0: 1574528})
Porosity of the sample: 0.196816
| MIT | code/postprocess/Sample Postprocessing.ipynb | miniminisu/dcgan-code-cu-foam-3D |
Measuring atmospheric pressure In this exercise we used a Sony XPeria phone's sensors with the [PhyPhox](https://phyphox.org/) application to measure ambient air pressure on a sunny summer day in southern France. We begin our descent from the Jura mountains at Col de la Fausille and end down at a parking lot at CERN's... | # Let's load the relevant python modules.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
# Load the relevant data.
baro = pd.read_csv("../../Data/barometri_fausille.csv")
# Take a look at the data.
baro.head()
# Since the data has only time and pressure, we'll calculate th... | _____no_output_____ | CC-BY-4.0 | Exercises-with-open-data/Other/barometer_col_de_la_fausille.ipynb | trongnghia00/cms |
[](http://introml.analyticsdojo.com)Introduction to Python - Groupby and Pivot Tablesintroml.analyticsdojo.com Groupby and Pivot Tables | !wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/train.csv
!wget https://raw.githubusercontent.com/rpi-techfundamentals/spring2019-materials/master/input/test.csv
import numpy as np
import pandas as pd
# Input data files are available in the "../input/" directory.
# Let'... | _____no_output_____ | MIT | site/_build/html/_sources/notebooks/02-intro-python/04-groupby.ipynb | rpi-techfundamentals/spring2020_website |
Groupby- Often it is useful to see statistics by different classes.- Can be used to examine different subpopulations | train.head()
print(train.dtypes)
#What does this tell us?
train.groupby(['Sex']).Survived.mean()
#What does this tell us?
train.groupby(['Sex','Pclass']).Survived.mean()
#What does this tell us? Here it doesn't look so clear. We could separate by set age ranges.
train.groupby(['Sex','Age']).Survived.mean() | _____no_output_____ | MIT | site/_build/html/_sources/notebooks/02-intro-python/04-groupby.ipynb | rpi-techfundamentals/spring2020_website |
Combining Multiple Operations- *Splitting* the data into groups based on some criteria- *Applying* a function to each group independently- *Combining* the results into a data structure | s = train.groupby(['Sex','Pclass'], as_index=False).Survived.sum()
s['PerSurv'] = train.groupby(['Sex','Pclass'], as_index=False).Survived.mean().Survived
s['PerSurv']=s['PerSurv']*100
s['Count'] = train.groupby(['Sex','Pclass'], as_index=False).Survived.count().Survived
survived =s.Survived
s
#What does this tell us? ... | _____no_output_____ | MIT | site/_build/html/_sources/notebooks/02-intro-python/04-groupby.ipynb | rpi-techfundamentals/spring2020_website |
Pivot Tables- A pivot table is a data summarization tool, much easier than the syntax of groupBy. - It can be used to that sum, sort, averge, count, over a pandas dataframe. - Download and open data in excel to appreciate the ways that you can use Pivot Tables. | #Load it and create a pivot table.
from google.colab import files
files.download('train.csv')
#List the index and the functions you want to aggregage by.
pd.pivot_table(train,index=["Sex","Pclass"],values=["Survived"],aggfunc=['count','sum','mean',]) | _____no_output_____ | MIT | site/_build/html/_sources/notebooks/02-intro-python/04-groupby.ipynb | rpi-techfundamentals/spring2020_website |
Notebook 2In this notebook, we worked with the result dataset from Notebook 1 and computed rolling statistics (mean, difference, std, max, min) for a list of features over various time windows. This was the most time consuming and computational expensive part of the entire tutorial. We encountered some roadblocks and... | import pyspark.sql.functions as F
import time
import subprocess
import sys
import os
import re
from pyspark import SparkConf
from pyspark import SparkContext
from pyspark import SQLContext
from pyspark.sql.types import *
from pyspark.sql.functions import col,udf,lag,date_add,explode,lit,concat,unix_timestamp
from pysp... | _____no_output_____ | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Define list of features for rolling compute, window sizes | rolling_features = [
'warn_type1_total', 'warn_type2_total',
'pca_1_warn','pca_2_warn', 'pca_3_warn', 'pca_4_warn', 'pca_5_warn',
'pca_6_warn','pca_7_warn', 'pca_8_warn', 'pca_9_warn', 'pca_10_warn',
'pca_11_warn','pca_12_warn', 'pca_13_warn', 'pca_14_warn', 'pca_15_warn',
'pca_16_warn','pca_17_war... | 46
| MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
What issues we encountered using Pyspark and how we solved them?- If the entire list of **46 features** and **5 time windows** were computed for **5 different types of rolling** (mean, difference, std, max, min) all in one go, we always ran into "StackOverFlow" error. - It was because the lineage was too long and Sp... | %%time
# Load result dataset from Notebook #1
df = sqlContext.read.parquet('/mnt/resource/PysparkExample/notebook1_result.parquet')
for lag_n in lags:
wSpec = Window.partitionBy('deviceid').orderBy('date').rowsBetween(1-lag_n, 0)
for col_name in rolling_features:
df = df.withColumn(col_name+'_rollingm... | Lag = 3, Column = warn_type1_total
Lag = 3, Column = warn_type2_total
Lag = 3, Column = pca_1_warn
Lag = 3, Column = pca_2_warn
Lag = 3, Column = pca_3_warn
Lag = 3, Column = pca_4_warn
Lag = 3, Column = pca_5_warn
Lag = 3, Column = pca_6_warn
Lag = 3, Column = pca_7_warn
Lag = 3, Column = pca_8_warn
Lag = 3, Column = ... | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Rolling Difference | %%time
# Load result dataset from Notebook #1
df = sqlContext.read.parquet('/mnt/resource/PysparkExample/notebook1_result.parquet')
for lag_n in lags:
wSpec = Window.partitionBy('deviceid').orderBy('date').rowsBetween(1-lag_n, 0)
for col_name in rolling_features:
df = df.withColumn(col_name+'_rollingd... | Lag = 3, Column = warn_type1_total
Lag = 3, Column = warn_type2_total
Lag = 3, Column = pca_1_warn
Lag = 3, Column = pca_2_warn
Lag = 3, Column = pca_3_warn
Lag = 3, Column = pca_4_warn
Lag = 3, Column = pca_5_warn
Lag = 3, Column = pca_6_warn
Lag = 3, Column = pca_7_warn
Lag = 3, Column = pca_8_warn
Lag = 3, Column = ... | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Rolling Std | %%time
# Load result dataset from Notebook #1
df = sqlContext.read.parquet('/mnt/resource/PysparkExample/notebook1_result.parquet')
for lag_n in lags:
wSpec = Window.partitionBy('deviceid').orderBy('date').rowsBetween(1-lag_n, 0)
for col_name in rolling_features:
df = df.withColumn(col_name+'_rollings... | Lag = 3, Column = warn_type1_total
Lag = 3, Column = warn_type2_total
Lag = 3, Column = pca_1_warn
Lag = 3, Column = pca_2_warn
Lag = 3, Column = pca_3_warn
Lag = 3, Column = pca_4_warn
Lag = 3, Column = pca_5_warn
Lag = 3, Column = pca_6_warn
Lag = 3, Column = pca_7_warn
Lag = 3, Column = pca_8_warn
Lag = 3, Column = ... | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Rolling Max | %%time
# Load result dataset from Notebook #1
df = sqlContext.read.parquet('/mnt/resource/PysparkExample/notebook1_result.parquet')
for lag_n in lags:
wSpec = Window.partitionBy('deviceid').orderBy('date').rowsBetween(1-lag_n, 0)
for col_name in rolling_features:
df = df.withColumn(col_name+'_rollingm... | Lag = 3, Column = warn_type1_total
Lag = 3, Column = warn_type2_total
Lag = 3, Column = pca_1_warn
Lag = 3, Column = pca_2_warn
Lag = 3, Column = pca_3_warn
Lag = 3, Column = pca_4_warn
Lag = 3, Column = pca_5_warn
Lag = 3, Column = pca_6_warn
Lag = 3, Column = pca_7_warn
Lag = 3, Column = pca_8_warn
Lag = 3, Column = ... | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Rolling Min | %%time
# Load result dataset from Notebook #1
df = sqlContext.read.parquet('/mnt/resource/PysparkExample/notebook1_result.parquet')
for lag_n in lags:
wSpec = Window.partitionBy('deviceid').orderBy('date').rowsBetween(1-lag_n, 0)
for col_name in rolling_features:
df = df.withColumn(col_name+'_rollingm... | Lag = 3, Column = warn_type1_total
Lag = 3, Column = warn_type2_total
Lag = 3, Column = pca_1_warn
Lag = 3, Column = pca_2_warn
Lag = 3, Column = pca_3_warn
Lag = 3, Column = pca_4_warn
Lag = 3, Column = pca_5_warn
Lag = 3, Column = pca_6_warn
Lag = 3, Column = pca_7_warn
Lag = 3, Column = pca_8_warn
Lag = 3, Column = ... | MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Join result dataset from the five rolling compute cells:- Join in Spark is usually very slow, it is better to reduce the number of partitions before the join.- Check the number of partitions of the pyspark dataframe.- **repartition vs coalesce**. If we only want to reduce the number of partitions, it is better to u... | # Import result dataset
rollingmean = sqlContext.read.parquet('/mnt/resource/PysparkExample/data_rollingmean.parquet')
rollingdiff = sqlContext.read.parquet('/mnt/resource/PysparkExample/rollingdiff.parquet')
rollingstd = sqlContext.read.parquet('/mnt/resource/PysparkExample/rollingstd.parquet')
rollingmax = sqlContex... | CPU times: user 901 ms, sys: 303 ms, total: 1.2 s
Wall time: 1h 50min 38s
| MIT | Notebook_2_FeatureEngineering_RollingCompute.ipynb | yallic/PySpark-Predictive-Maintenance |
Are Graphs Unique?This notebook shows how to determine if each entry in the HydroNet dataset represents a unique graph. | %matplotlib inline
from matplotlib import pyplot as plt
from hydronet.data import graph_from_dict
from multiprocessing import Pool
from functools import partial
from tqdm import tqdm
import networkx as nx
import pandas as pd
import numpy as np | _____no_output_____ | Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Configuration | cluster_size = 18 | _____no_output_____ | Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Load in the DataLoad in a small dataset from disk | %%time
data = pd.read_json('../data/output/atomic_valid.json.gz', lines=True)
print(f'Loaded {len(data)} records') | Loaded 224018 records
CPU times: user 33.1 s, sys: 5.7 s, total: 38.8 s
Wall time: 38.8 s
| Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Find Pairs of Isomorphic GraphsAssess how many training records are isomorphic | data.query(f'n_waters=={cluster_size}', inplace=True)
print(f'Downselected to {len(data)} graphs') | Downselected to 5714 graphs
| Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Generate networkx objects for each | %%time
data['nx'] = data.apply(graph_from_dict, axis=1) | CPU times: user 1.66 s, sys: 170 ms, total: 1.83 s
Wall time: 1.83 s
| Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Compute which graphs are isomorphic | data.reset_index(inplace=True)
matches = [[] for _ in range(len(data))]
n_matches = 0
with Pool() as p:
for i, g in tqdm(enumerate(data['nx']), total=len(data)):
f = partial(nx.algorithms.is_isomorphic, g, node_match=dict.__eq__, edge_match=dict.__eq__)
is_match = p.map(f, data['nx'].iloc[i+1:])
... | 100%|██████████| 5714/5714 [26:46<00:00, 3.56it/s]
| Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Add to the dataframe for safe keeping | data['matches'] = matches
data['n_matches'] = data['matches'].apply(len) | _____no_output_____ | Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Assess Energy Differences between Isomorphic GraphsWe want to know how large they are. Does each graph represent a local minimum, or they actually very different in energy? | energy_diffs = []
for rid, row in data.query('n_matches>0').iterrows():
for m in row['matches']:
if m > rid:
energy_diffs.append(abs(row['energy'] - data.iloc[m]['energy']))
print(f'Maximum: {np.max(energy_diffs):.2e} kcal/mol')
print(f'Median: {np.percentile(energy_diffs, 50):.2e} kcal/mol')
p... | _____no_output_____ | Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
For comparision, print out the range of energies for clusters | (data['energy'] - data['energy'].min()).describe() | _____no_output_____ | Apache-2.0 | misc/are-unique-graphs-unique-clusters.ipynb | exalearn/hydronet |
Interactive question answering with OpenVINOThis demo shows interactive question answering with OpenVINO. We use [small BERT-large-like model](https://github.com/openvinotoolkit/open_model_zoo/tree/master/models/intel/bert-small-uncased-whole-word-masking-squad-int8-0002) distilled and quantized to INT8 on SQuAD v1.1 ... | import time
from urllib import parse
import numpy as np
from openvino.runtime import Core, Dimension
import html_reader as reader
import tokens_bert as tokens | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
The model Download the modelWe use `omz_downloader`, which is a command-line tool from the `openvino-dev` package. `omz_downloader` automatically creates a directory structure and downloads the selected model. If the model is already downloaded, this step is skipped.You can download and use any of the following models... | # directory where model will be downloaded
base_model_dir = "model"
# desired precision
precision = "FP16-INT8"
# model name as named in Open Model Zoo
model_name = "bert-small-uncased-whole-word-masking-squad-int8-0002"
model_path = f"model/intel/{model_name}/{precision}/{model_name}.xml"
model_weights_path = f"mod... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Load the modelDownloaded models are located in a fixed structure, which indicates vendor, model name and precision. Only a few lines of code are required to run the model. First, we create an Inference Engine object. Then we read the network architecture and model weights from the .xml and .bin files. Finally, we comp... | # initialize inference engine
ie_core = Core()
# read the model and corresponding weights from file
model = ie_core.read_model(model=model_path, weights=model_weights_path)
# assign dynamic shapes to every input layer
for input_layer in model.inputs:
input_shape = input_layer.partial_shape
input_shape[1] = Di... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Input keys are the names of the input nodes and output keys contain names of output nodes of the network. In the case of the BERT-large-like model, we have four inputs and two outputs. | [i.any_name for i in input_keys], [o.any_name for o in output_keys] | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
ProcessingNLP models usually take a list of tokens as standard input. A token is a single word converted to some integer. To provide the proper input, we need the vocabulary for such mapping. We also define some special tokens like separators and a function to load the content from provided URLs. | # path to vocabulary file
vocab_file_path = "data/vocab.txt"
# create dictionary with words and their indices
vocab = tokens.load_vocab_file(vocab_file_path)
# define special tokens
cls_token = vocab["[CLS]"]
sep_token = vocab["[SEP]"]
# function to load text from given urls
def load_context(sources):
input_url... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
PreprocessingThe main input (`input_ids`) to used BERT model consist of two parts: question tokens and context tokens separated by some special tokens. We also need to provide: `attention_mask`, which is a sequence of integer values representing the mask of valid values in the input; `token_type_ids`, which is a seque... | # generator of a sequence of inputs
def prepare_input(question_tokens, context_tokens, input_keys):
input_ids = [cls_token] + question_tokens + [sep_token] + context_tokens + [sep_token]
# 1 for any index
attention_mask = [1] * len(input_ids)
# 0 for question tokens, 1 for context part
token_type_id... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
PostprocessingThe results from the network are raw (logits). We need to use the softmax function to get the probability distribution. Then, we are looking for the best answer in the current part of the context (the highest score) and we return the score and the context range for the answer. | # based on https://github.com/openvinotoolkit/open_model_zoo/blob/bf03f505a650bafe8da03d2747a8b55c5cb2ef16/demos/common/python/openvino/model_zoo/model_api/models/bert.py#L163
def postprocess(output_start, output_end, question_tokens, context_tokens_start_end, input_size):
def get_score(logits):
out = np.e... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Firstly, we need to create a list of tokens from the context and the question. Then, we are looking for the best answer in the context. The best answer should come with the highest score. | def get_best_answer(question, context, vocab, input_keys):
# convert context string to tokens
context_tokens, context_tokens_start_end = tokens.text_to_tokens(text=context.lower(),
vocab=vocab)
# convert question string to tokens
quest... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Main Processing FunctionRun question answering on specific knowledge base and iterate through the questions. | def run_question_answering(sources):
print(f"Context: {sources}", flush=True)
context = load_context(sources)
if len(context) == 0:
print("Error: Empty context or outside paragraphs")
return
while True:
question = input()
# if no question - break
if question == ... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Run Run on local paragraphsChange sources to your own to answer your questions. You can use as many sources as you want. Usually, you need to wait a few seconds for the answer, but the longer context the longer the waiting time. The model is very limited and sensitive for the input. The answer can depend on whether th... | sources = ["Computational complexity theory is a branch of the theory of computation in theoretical computer "
"science that focuses on classifying computational problems according to their inherent difficulty, "
"and relating those classes to each other. A computational problem is understood to b... | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Run on websitesYou can also provide urls. Note that the context (knowledge base) is built from website paragraphs. If some information is outside the paragraphs, the algorithm won't able to find it.Sample source: [OpenVINO wiki](https://en.wikipedia.org/wiki/OpenVINO)Sample questions:- What does OpenVINO mean?- What i... | sources = ["https://en.wikipedia.org/wiki/OpenVINO"]
run_question_answering(sources) | _____no_output_____ | Apache-2.0 | notebooks/213-question-answering/213-question-answering.ipynb | mzegla/openvino_notebooks |
Laboratorio 10 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import plo... | _____no_output_____ | MIT | labs/lab10.ipynb | AlvaroMarambio/mat281_portfolio |
Ejercicio 1(1 pto.)Ajusta una regresión logística a los datos de entrenamiento y obtén el _accuracy_ con los datos de test. Utiliza el argumento `n_jobs` igual a $-1$, si aún así no converge aumenta el valor de `max_iter`.Hint: Recuerda que el _accuracy_ es el _score_ por defecto en los modelos de clasificación de sci... | # No hay que hace validacion cruzada pq la regresion logistica no tiene hiperparametros
lr = LogisticRegression(max_iter=2100, n_jobs=-1) # ya con 2100 iteraciones aproximadamente converge aproximadamente al mismo valor que con mas iteraciones
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
print(f"Logistic Regr... | Logistic Regression accuracy: 0.98
| MIT | labs/lab10.ipynb | AlvaroMarambio/mat281_portfolio |
Ejercicio 2(1 pto.)Utiliza `GridSearchCV` con 5 _folds_ para encontrar el mejor valor de `n_neighbors` de un modelo KNN. | knn =KNeighborsClassifier() # Defino el modelo de KNN
knn_grid = {"n_neighbors": np.arange(2, 31)} # Defino una grilla
knn_cv = GridSearchCV( # Hago validacion cruzada
KNeighborsClassifier(), # modelo a hiperparametrizar
param_grid=knn_grid, #defino la grilla a utilizar
cv=5, # Defino los ... | KNN accuracy: 0.96
| MIT | labs/lab10.ipynb | AlvaroMarambio/mat281_portfolio |
Ejercicio 3(1 pto.)¿Cuál modelo escogerías basándote en los resultados anteriores? Justifica __Respuesta:__ El mejor modelo de los dos utilizados es el de regresion logistica ya que tiene un accuracy de 0.98 con 2100 iteraciones en comparacion con el de KNN que tiene un accuracy de 0.96 utilizando 5 fold. Ejercicio 4... | # Me quedo con el modelo de regresion logistica
plot_confusion_matrix(lr, X_test, y_test, display_labels=target_names) # en vez de tirar 0 y 1 te salagan valores reales malignt bening
plt.show()
# Uso el y_pred que definí en el modelo de regresion logistica
print(classification_report(y_test, y_pred, target_names=bre... | precision recall f1-score support
malignant 0.97 0.97 0.97 63
benign 0.98 0.98 0.98 108
accuracy 0.98 171
macro avg 0.97 0.97 0.97 171
weighted avg 0.98 0.98 0.98 ... | MIT | labs/lab10.ipynb | AlvaroMarambio/mat281_portfolio |
Chapter 11 - Machine LearningWoo! machinelearning ml AI Data science is a lot of reformatting of business problems into data problems, and then collecting, cleaning, formatting, and restructuring data. ML is almost an afterthought. But it is an essential afterthought. Intro to this chapter is a good one. | # supervised models
# need to create some learnin data
def split_data(data, prob):
results = [], []
for row in data:
results[0 if random.random() < prob else 1].append(row)
return results
def train_test_split(x, y, test_pct):
data = zip(x,y)
train, test = split_data(data, 1 - test_pct)
... | _____no_output_____ | MIT | DSFS Chapter 11 - Machine Learning.ipynb | Kladar/dsfs |
Models aren't necessarily graded on accuracy. If we said every person named Luke will not develop leukemia, we'd be right 98% of the time.See the book (or a google search) for the confusion matrix, which describes true positives, true negatives, false positives (Type I error), and false negatives (Type 2 error) | def accuracy(tp, fp, fn, tn):
correct = tp + tn
total = tp+tn+fp+fn
return correct / total
print(accuracy(70, 4930, 13930, 981070))
# precision is accuracy of positive predictions
def precision(tp, fp, fn, tn):
return tp / (tp+fp)
print(precision(70,4930,13930,981070))
# recall is the fraction of the ... | 0.00736842105263158
| MIT | DSFS Chapter 11 - Machine Learning.ipynb | Kladar/dsfs |
Annotating pathway into mouse Single-Cell clustersThis tutorial shows how to use the descartes_rpa module with scanpy formated data outside of Descartes. Data from the [Trajectory inference for hematopoiesis in mouse](https://scanpy-tutorials.readthedocs.io/en/latest/paga-paul15.html) tutorial will be used. | import scanpy as sc
adata = sc.datasets.paul15()
adata.X = adata.X.astype('float64') # this is not required and results will be comparable without it
sc.pp.recipe_zheng17(adata)
sc.tl.pca(adata, svd_solver='arpack')
sc.pp.neighbors(adata, n_neighbors=4, n_pcs=20)
sc.tl.leiden(adata) | _____no_output_____ | Apache-2.0 | demo/mouse_data.ipynb | reactome/descartes |
Since this dataset is from mouse (Mus musculus), we pass its species as input | from descartes_rpa import get_pathways_for_group
get_pathways_for_group(adata, groupby="paul15_clusters", species="Mus musculus") | /home/joao/miniconda3/envs/descartes-rpa/lib/python3.9/site-packages/scanpy/tools/_rank_genes_groups.py:419: RuntimeWarning: invalid value encountered in log2
self.stats[group_name, 'logfoldchanges'] = np.log2(
| Apache-2.0 | demo/mouse_data.ipynb | reactome/descartes |
We can look at the top 2 marker genes for each cluster | from descartes_rpa.pl import marker_genes
marker_genes(adata, n_genes=2) | WARNING: dendrogram data not found (using key=dendrogram_paul15_clusters). Running `sc.tl.dendrogram` with default parameters. For fine tuning it is recommended to run `sc.tl.dendrogram` independently.
WARNING: saving figure to file dotplot_marker_genes.pdf
| Apache-2.0 | demo/mouse_data.ipynb | reactome/descartes |
Also, we can look at the shared pathways between clusters | from descartes_rpa.pl import shared_pathways
shared_pathways(adata, clusters=["9GMP", "1Ery", "17Neu", "4Ery"])
from descartes_rpa import get_shared
get_shared(adata, clusters=["1Ery", "4Ery"])
from descartes_rpa.pl import pathways
adata.uns["pathways"].keys()
pathways(adata, "18Eos")
pathways(adata, "3Ery") | _____no_output_____ | Apache-2.0 | demo/mouse_data.ipynb | reactome/descartes |
Djibouti* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Djibouti.ipynb) | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview("Djibouti", weeks=5);
overview("Djibouti");
compare_plot("Djibouti", normalise=... | _____no_output_____ | CC-BY-4.0 | ipynb/Djibouti.ipynb | oscovida/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Djibouti.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on ho... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Djibouti.ipynb | oscovida/oscovida.github.io |
Linear regression without scikit-learnIn this notebook, we introduce linear regression. Before presenting theavailable scikit-learn classes, we will provide some insights with a simpleexample. We will use a dataset that contains information about penguins. NoteIf you want a deeper overview regarding this dataset, you ... | import pandas as pd
penguins = pd.read_csv("../datasets/penguins_regression.csv")
penguins.head() | _____no_output_____ | CC-BY-4.0 | notebooks/linear_regression_without_sklearn.ipynb | brospars/scikit-learn-mooc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.