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 |
|---|---|---|---|---|---|
d) CHECK AS TABLE (MANUAL CALCULATION): TO SEE CLEARLY WHAT HAPPENS | example_df_bstrap, example_df_summ_bstrap = result_summ(cluster_proportion_df=cluster_proportion_df_bstrap,
demand=demand_bstrap, weight=weight_bstrap,
sell_price=sell_price, cost_price=cost_price,
... | _____no_output_____ | BSD-3-Clause | misc - work/stochastic_ml_blend.ipynb | jkapila/paper-codebase |
d) VISUAL CHECK | example_df_bstrap.loc[:,'item_to_purchase'] = example_df_bstrap['item_to_purchase'].astype('str')
# check the weighted profit per possible scenario:
# we can see how higher execution causes greater loss during weak demand and hence,
# higher execution number has difficulty in bouncing the profit up
fig, ax = plt.sub... | _____no_output_____ | BSD-3-Clause | misc - work/stochastic_ml_blend.ipynb | jkapila/paper-codebase |
Prepare papermill for schulung3.geomar.de1. Make sure you have activated the correct kernel2. Install kernel manually | !python -m ipykernel install --user --name py3_lagrange_v2.2.2
!jupyter kernelspec list | [ListKernelSpecs] WARNING | Config option `kernel_spec_manager_class` not recognized by `ListKernelSpecs`.
Available kernels:
conda-env-monitoring-py /home/jupyter-wrath/.local/share/jupyter/kernels/conda-env-monitoring-py
conda-env-py3_euler-py /home/jupyter-wra... | MIT | Prepare_papermill_schulung3.ipynb | geomar-od-lagrange/papermill-demo |
Run papermill on schulung3.geomar.de | !papermill original_notebooks/01_papermill_demo.ipynb evaluated_notebooks/01_papermill_demo.ipynb -k py3_lagrange_v2.2.2 | Input Notebook: original_notebooks/01_papermill_demo.ipynb
Output Notebook: evaluated_notebooks/01_papermill_demo.ipynb
Executing: 0%| | 0/6 [00:00<?, ?cell/s]Executing notebook with kernel: py3_lagrange_v2.2.2
Executing: 100%|████████████████████████████████| 6/6 [00:02<00:00,... | MIT | Prepare_papermill_schulung3.ipynb | geomar-od-lagrange/papermill-demo |
Intraday Trading via Day Trading Techniques & Indicators--- Data collected via AlphaVantage free API using extended intraday data. > https://www.alphavantage.co/documentation/--- 03 - Exploratory Data Analysis Library Imports | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('fivethirtyeight')
from pandas.plotting import autocorrelation_plot
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.tsa.s... | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
Read in Filtered Dataset | df = pd.read_csv('../01_Data/extended_intraday_SPY_1min_filtered.csv')
df.set_index(pd.DatetimeIndex(df['time']), inplace=True)
df.drop(columns = ['time'], inplace = True)
df.head() | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
Feature Exploration Let's first look at our most important feature, 'close' price. | plt.figure(figsize=(18,9))
plt.plot(df['close']); | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
**We see the large drop from COVID in early 2020, but overall nothing that would upset our models.**---**Is our data stationary?**To answer this question, we apply the Augmented Dickey-Fuller Test and the accompanying function written by Joseph Nelson. | interpret_dftest(adfuller(df['close'])) | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
>With a p value of .92, our data is most definitely NOT stationary. For an ARIMA model, we need our data to be stationary.**To achieve Stationarity, we apply the .diff() function to observe the changes rather than prices.** | plt.figure(figsize=(18,9))
plt.plot(df['close'].diff());
interpret_dftest(adfuller(df['close'].diff().dropna())) | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
>With a p value of 0, our data is stationary. | df['close_first_diff'] = df['close'].diff()
df.head() | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
To avoid any issues created through our diff function, we will remove null values from our dataset. | df.shape
df.dropna(inplace=True)
df.shape | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
As expected, this only removed the first row due to the null value created from our diff function. **Does our data have seasonality?** | decomp = seasonal_decompose(df['close'], period=1)
with plt.rc_context():
plt.rc("figure", figsize=(18,9))
# Plot the decomposed time series.
decomp.plot(); | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
> Difficult to tell from this visual alone. We do not appear to have significant seasonality, but let's continue to analyze. | autocorrelation_plot(df['close']);
plot_acf(df['close'], lags=452);
plot_pacf(df['close'], lags=452); | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
**These are difficult to interpret. Because we have such a large amount of data on 1minute intervals, its difficult to visualize a useful correlation tool.****We are focusing on intraday data, however, so let's try picking a random day and testing correlation inside of a day.** | test = df.query("time >= '2019-10-28' and time < '2019-10-29'")
test.shape | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
We see that a typical day consists of 450 minute intervals, or about 7.5 hours. When considering that we wanted our time frame to be 9:00am to 4:30pm, we again see the 7.5 hours. So we know this was a correct split for a single day. | df.shape
df.shape[0] / 450
decomp = seasonal_decompose(test['close'], period=1)
with plt.rc_context():
plt.rc("figure", figsize=(18,9))
# Plot the decomposed time series.
decomp.plot();
autocorrelation_plot(test['close']);
plot_acf(test['close'], lags=448);
plot_pacf(test['close'], lags=223); | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
>These results are much easier to interpret. We see there is not significant correlation between close prices beyond the initial few lags, which is to be expected. Target Variable**Our target variable is split into 3 columns.**1. 'target' shows us the % move in 1 minute (already multiplied by 100)2. 'target_binary_cla... | df['target'].describe() | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
**Our mean move is only 0.000095%, even after removing most of the pre-market and after hours data.****However, our standard deviation is 0.056% which quickly incorporates most of our values.**- **3 standard deviations from our mean of about 0 would be +/- 0.168**---This is described better visually: | plt.figure(figsize=(18,9))
df['target'].hist(bins=1000)
plt.xlim(-0.2,0.2)
plt.ylabel('Occurances')
plt.xlabel('Price Movements in 1 Minute')
plt.title('Distribution of Target Variable'); | _____no_output_____ | MIT | 00_Code/03_ExploratoryDataAnalysis.ipynb | bvarnam/StockPrediction |
Copyright (c) Microsoft Corporation. All rights reserved.Licensed under the MIT License. 
print("You are currently using version", azureml.core.VERSION, "of the Azure ML SDK")
ws = Workspace.from_config()
# Choose a name for the experiment.
experiment_name = 'automl-regression-hardware-explain'
experiment = Experiment(ws, experiment... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Create or Attach existing AmlComputeYou will need to create a [compute target](https://docs.microsoft.com/azure/machine-learning/service/concept-azure-machine-learning-architecturecompute-target) for your AutoML run. In this tutorial, you create `AmlCompute` as your training compute resource.**Creation of AmlCompute t... | from azureml.core.compute import ComputeTarget, AmlCompute
from azureml.core.compute_target import ComputeTargetException
# Choose a name for your cluster.
amlcompute_cluster_name = "hardware-cluster"
# Verify that cluster does not exist already
try:
compute_target = ComputeTarget(workspace=ws, name=amlcompute_cl... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Setup Training and Test Data for AutoML experimentLoad the hardware dataset from a csv file containing both training features and labels. The features are inputs to the model, while the training labels represent the expected output of the model. Next, we'll split the data using random_split and extract the training da... | data = 'https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv'
dataset = Dataset.Tabular.from_delimited_files(data)
# Split the dataset into train and test datasets
train_data, test_data = dataset.random_split(percentage=0.8, seed=223)
# Register the train dataset with y... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
TrainInstantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.|Property|Description||-|-||**task**|classification, regression or forecasting||**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: spearman_correlationn... | featurization_config = FeaturizationConfig()
featurization_config.blocked_transformers = ['LabelEncoder']
#featurization_config.drop_columns = ['MMIN']
featurization_config.add_column_purpose('MYCT', 'Numeric')
featurization_config.add_column_purpose('VendorName', 'CategoricalHash')
#default strategy mean, add transfor... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Call the `submit` method on the experiment object and pass the run configuration. Execution of local runs is synchronous. Depending on the data and the number of iterations this can run for a while.In this example, we specify `show_output = True` to print currently running iterations to the console. | remote_run = experiment.submit(automl_config, show_output = False)
remote_run | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Run the following cell to access previous runs. Uncomment the cell below and update the run_id. | #from azureml.train.automl.run import AutoMLRun
#remote_run = AutoMLRun(experiment=experiment, run_id='<run_ID_goes_here')
#remote_run
remote_run.wait_for_completion()
best_run, fitted_model = remote_run.get_output()
best_run_customized, fitted_model_customized = remote_run.get_output() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
TransparencyView updated featurization summary | custom_featurizer = fitted_model_customized.named_steps['datatransformer']
custom_featurizer.get_featurization_summary() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
is_user_friendly=False allows for more detailed summary for transforms being applied | custom_featurizer.get_featurization_summary(is_user_friendly=False)
custom_featurizer.get_stats_feature_type_summary() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Results Widget for Monitoring RunsThe widget will first report a "loading" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.**Note:** The wi... | from azureml.widgets import RunDetails
RunDetails(remote_run).show() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
ExplanationsThis step requires an Enterprise workspace to gain access to this feature. To learn more about creating an Enterprise workspace or upgrading to an Enterprise workspace from the Azure portal, please visit our [Workspace page.](https://docs.microsoft.com/azure/machine-learning/service/concept-workspaceupgrad... | automl_run, fitted_model = remote_run.get_output(metric='r2_score') | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Setup model explanation run on the remote computeThe following section provides details on how to setup an AzureML experiment to run model explanations for an AutoML model on your remote compute. Sample script used for computing explanationsView the sample script for computing the model explanations for your AutoML m... | with open('train_explainer.py', 'r') as cefr:
print(cefr.read()) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Substitute values in your sample scriptThe following cell shows how you change the values in the sample script so that you can change the sample script according to your experiment and dataset. | import shutil
import os
# create script folder
script_folder = './sample_projects/automl-regression-hardware'
if not os.path.exists(script_folder):
os.makedirs(script_folder)
# Copy the sample script to script folder.
shutil.copy('train_explainer.py', script_folder)
# Create the explainer script that will run on... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Create conda configuration for model explanations experiment from automl_run object | from azureml.core.runconfig import RunConfiguration
from azureml.core.conda_dependencies import CondaDependencies
import pkg_resources
# create a new RunConfig object
conda_run_config = RunConfiguration(framework="python")
# Set compute target to AmlCompute
conda_run_config.target = compute_target
conda_run_config.en... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Submit the experiment for model explanationsSubmit the experiment with the above `run_config` and the sample script for computing explanations. | # Now submit a run on AmlCompute for model explanations
from azureml.core.script_run_config import ScriptRunConfig
script_run_config = ScriptRunConfig(source_directory=script_folder,
script='train_explainer.py',
run_config=conda_run_config)
run =... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Feature importance and visualizing explanation dashboardIn this section we describe how you can download the explanation results from the explanations experiment and visualize the feature importance for your AutoML model on the azure portal. Download engineered feature importance from artifact storeYou can use *Exp... | from azureml.explain.model._internal.explanation_client import ExplanationClient
client = ExplanationClient.from_run(automl_run)
engineered_explanations = client.download_model_explanation(raw=False, comment='engineered explanations')
print(engineered_explanations.get_feature_importance_dict())
print("You can visualize... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Download raw feature importance from artifact storeYou can use *ExplanationClient* to download the raw feature explanations from the artifact store of the *automl_run*. You can also use azure portal url to view the dash board visualization of the feature importance values of the raw features. | raw_explanations = client.download_model_explanation(raw=True, comment='raw explanations')
print(raw_explanations.get_feature_importance_dict())
print("You can visualize the raw explanations under the 'Explanations (preview)' tab in the AutoML run at:-\n" + automl_run.get_portal_url()) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
OperationailzeIn this section we will show how you can operationalize an AutoML model and the explainer which was used to compute the explanations in the previous section. Register the AutoML model and the scoring explainerWe use the *TreeScoringExplainer* from *azureml.explain.model* package to create the scoring exp... | # Register trained automl model present in the 'outputs' folder in the artifacts
original_model = automl_run.register_model(model_name='automl_model',
model_path='outputs/model.pkl')
scoring_explainer_model = automl_run.register_model(model_name='scoring_explainer',
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Create the conda dependencies for setting up the serviceWe need to create the conda dependencies comprising of the *azureml-explain-model*, *azureml-train-automl* and *azureml-defaults* packages. | conda_dep = automl_run.get_environment().python.conda_dependencies
with open("myenv.yml","w") as f:
f.write(conda_dep.serialize_to_string())
with open("myenv.yml","r") as f:
print(f.read()) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
View your scoring file | with open("score_explain.py","r") as f:
print(f.read()) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Deploy the serviceIn the cell below, we deploy the service using the conda file and the scoring file from the previous steps. | from azureml.core.webservice import Webservice
from azureml.core.model import InferenceConfig
from azureml.core.webservice import AciWebservice
from azureml.core.model import Model
from azureml.core.environment import Environment
aciconfig = AciWebservice.deploy_configuration(cpu_cores=1,
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
View the service logs | service.get_logs() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Inference using some test dataInference using some test data to see the predicted value from autml model, view the engineered feature importance for the predicted value and raw feature importance for the predicted value. | if service.state == 'Healthy':
X_test = test_data.drop_columns([label]).to_pandas_dataframe()
# Serialize the first row of the test data into json
X_test_json = X_test[:1].to_json(orient='records')
print(X_test_json)
# Call the service to get the predictions and the engineered and raw explanations
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Delete the serviceDelete the service once you have finished inferencing. | service.delete() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
Test | # preview the first 3 rows of the dataset
test_data = test_data.to_pandas_dataframe()
y_test = test_data['ERP'].fillna(0)
test_data = test_data.drop('ERP', 1)
test_data = test_data.fillna(0)
train_data = train_data.to_pandas_dataframe()
y_train = train_data['ERP'].fillna(0)
train_data = train_data.drop('ERP', 1)
tra... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-explanation-featurization/auto-ml-regression-explanation-featurization.ipynb | jpe316/MachineLearningNotebooks |
%matplotlib inline
from __future__ import print_function
#%matplotlib inline
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision... | _____no_output_____ | MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN | |
Extract 1D signal from flow field | train_sigs = field[:,0].reshape(field.shape[0]*128*128,1,128)
plt.plot(train_sigs[np.random.randint(0,train_sigs.shape[0]),0])
print(torch.mean(train_sigs[:,0]))
print(torch.std(train_sigs[:,0]))
def auto_cor(v):
v = v.detach()
result = 0
for i in range(v.shape[0]):
result += np.correlate(v[i],v[i],mode='full... | _____no_output_____ | MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
Learning 1D Turbulent signal with GAN | # Set random seem for reproducibility
manualSeed = 999
#manualSeed = random.randint(1, 10000) # use if you want new results
print("Random Seed: ", manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
# Batch size during training
batch_size = 128
# Size of z latent vector (i.e. size of generator input)
nz ... | _____no_output_____ | MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
Generator | class Generator(nn.Module):
def __init__(self,ngpu):
super(Generator, self).__init__()
self.ngpu = ngpu
self.hidden_dim = 256
self.lstm_cell = nn.LSTMCell(1+1,self.hidden_dim)
self.fc2 = nn.Sequential(
nn.Linear(self.hidden_dim,1,bias=False),
)
def... | _____no_output_____ | MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
Discriminator | class Discriminator(nn.Module):
def __init__(self, ngpu):
super(Discriminator, self).__init__()
self.ngpu = ngpu
self.main = nn.Sequential(
# input is nz x 1 x 1
(nn.Conv2d(128, 64 * 4, (5,1), (2,1), (2,0), bias=False)),
nn.LeakyReLU(0.2,inplace=True),
... | tensor(-0.0002, device='cuda:0', grad_fn=<MeanBackward0>)
tensor([[[[-0.0006]]],
[[[-0.0004]]],
[[[-0.0003]]],
...,
[[[-0.0001]]],
[[[-0.0002]]],
[[[-0.0003]]]], device='cuda:0', grad_fn=<CudnnConvolutionBackward>)
| MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
GAN | # Initialize loss function
def criterion(y):
return torch.mean(y)
# Setup Adam optimizers for both G and D
betas=(beta1, 0.9)
optimizerD = optim.Adam(netD.parameters(), lr=lr,betas=betas)
optimizerG = optim.Adam(netG.parameters(), lr=lr,betas=betas)
mean_real = torch.mean(train_sigs,dim=0)
def stat_constraint(x):
... | _____no_output_____ | MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
Results | device = torch.device("cpu")
netG.to(device)
netG.eval()
netG.requires_grad_(False)
num_examples_to_generate = 128*128
#Generate u
manualSeed = random.randint(1, 10000) # use if you want new results
random.seed(manualSeed)
torch.manual_seed(manualSeed)
noise = torch.randn(num_examples_to_generate,nz,128, device=device... | tensor(-0.0028)
tensor(0.2065)
| MIT | lstm_gan_isoturb1D.ipynb | ferngonzalezp/turbulence-GAN |
说明: 给定一个二叉树,计算整个树的坡度。 一个树的节点的坡度定义即为: 该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。 整个树的坡度就是其所有节点的坡度之和。示例: 输入: 1 / \ 2 3 输出:1 解释: 结点 2 的坡度: 0 结点 3 的坡度: 0 结点 1 的坡度: |2-3| = 1 树的坡度 : 0 + 0 + 1 = 1 提示: 1、任何子树的结点的和不会超过 32 位整数的范围。 2、坡度的值不会超过 32 位整数的范围。 | def __init__(self):
self.tilt = 0
def findTilt(self, root: TreeNode) -> int:
# null node equals to node whose value is 0
self.calc(root)
return self.tilt
def calc(self, root):
if not root:
return 0
l = r = 0
if root.left:
l = self.calc(root.left)
if root.right:
... | _____no_output_____ | Apache-2.0 | Tree/1020/563. Binary Tree Tilt.ipynb | YuHe0108/Leetcode |
High Resolution Conflict Forecasting with Spatial Convolutions and Long Short-Term Memory Replication Archive[Benjamin J. Radford](https://www.benradford.com) Assistant Professor UNC Charlotte bradfor7@uncc.edu This file produces all necessary data for the feature dropout study. **Warning:** This file may take s... | import sys
import os
import gc
import logging
import pandas as pd
import numpy as np
from datetime import datetime
from sklearn.ensemble import RandomForestRegressor
from joblib import dump, load
from itertools import product
from math import isnan
import views
from views import Period, Model, Downsampling
from vie... | _____no_output_____ | MIT | supplemental_replication_files/feature_dropout/run_feature_dropout.ipynb | benradford/high-resolution-conflict-forecasting |
Decisions:* Will just consider data form 2014 to 2021 because before that only a few districts were reporting**TO DO*** find coordinates * if cannot find locations, find random coordinates in the mentioned district* categorize incidents: * attack (against individuals) * physical (or physical + verba... | with open('../berlin_streets_dict.pickle', 'rb') as f:
berlin_streets_dics = pickle.load(f)
len(berlin_streets_dics['Straße']) | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Load pickled df_complete | with open('pickles/df_complete.pickle', 'rb') as f:
df_complete = pickle.load(f)
df_complete.loc[11041]['Story'] | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Load pickled df_lgbt | with open('df_lgbt.pickle', 'rb') as f:
df_lgbt = pickle.load(f)
df_complete | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Select df | # Only cases between 2014 and 2021
df_2014_2021 = df_complete[df_complete['Date'].dt.year >= 2014][['Date', 'District', 'Header', 'Story', 'Source']]
df_2014_2021.shape
# only cases that mention violence against LGBTQI* people in header OR in story
lgbt_lexicon = 'heteronormativ|gay|lgbt|lgtb|lbgt|ltgb|lgbqt|schwul|sch... | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Fill missing values | df_lgbt[df_lgbt['District'].isna() == True]
df_lgbt[df_lgbt['District'].isna() == True]
# df_lgbt['District'].loc[4512] = 'Charlottenburg-Wilmersdorf'
# df_lgbt['District'].loc[2421] = 'Mitte'
# pickle df_lgbt
with open('df_lgbt.pickle', 'wb') as f:
pickle.dump(df_lgbt, f) | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Add classifiers | # Add columns with np.nan
df_lgbt['Reported status'] = [np.nan for x in range(len(df_lgbt))] | <ipython-input-587-39245ea6712c>:1: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-c... | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
**Physical Attack** | filter_words = 'angriff|attack'
df_physical_attacks = df_lgbt[(df_lgbt['Header'].str.contains(filter_words, flags=re.IGNORECASE) == True)|(df_lgbt['Story'].str.contains(filter_words, flags=re.IGNORECASE) == True)]
physical_attack_indices = df_physical_attacks.index
physical_attack_indices
for i in attack_indices:
d... | /opt/anaconda3/lib/python3.8/site-packages/pandas/core/indexing.py:1765: 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: https://pandas.pydata.org/pandas-docs/stable/user_guide/inde... | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
**Verbal Attack** | df_without_physical_attacks = (df_lgbt[df_lgbt['Attack'].isna() == True])
filter_words = 'beleidig|beschimpf|bedroh'
df_verbal_attacks = df_without_physical_attacks[(df_without_physical_attacks['Header'].str.contains(filter_words, flags=re.IGNORECASE) == True)|(df_without_physical_attacks['Story'].str.contains(filter_w... | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Add coordinates | from geopy.geocoders import Nominatim
loc = Nominatim(user_agent="mymap").geocode("europacenter")
loc.address
coord = loc.latitude, loc.longitude
coord
df_2014_2021_attacks[df_2014_2021_attacks['Story'].str.contains(lgbt_lexicon, flags=re.IGNORECASE) == True]
df_2020_monthly_district = df_2020.groupby(['District', df_... | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Add District (Mitte) to missing value index= 2421 | df_2014_2021_lgbt_attacks[df_2014_2021_lgbt_attacks['District'].isna() == True]['Story'].iloc[0]
df_2014_2021_lgbt_attacks[df_2014_2021_lgbt_attacks['District'].isna() == True]
df_2014_2021_lgbt_attacks.loc[2421, 'District'] = 'Mitte'
df_2014_2021_lgbt_attacks.loc[2421]
df_2014_2021_lgbt_attacks.iloc[-100:-50]
df_2014_... | <ipython-input-614-241ff01241a7>:2: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
df_2014_2021_lgbt_attacks[df_2014_2021_lgbt_attacks['District'] == 'Neukölln'][df_2014_2021_lgbt_attacks['Date'] == '2020-04-12']['Story'].iloc[0]
| MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Check for references to Turks or Arabs | df_2014_2021_lgbt_attacks[df_2014_2021_lgbt_attacks['Story'].str.contains('arab|turk') == True]['Date']
df_2014_2021_lgbt_attacks[df_2014_2021_lgbt_attacks['Date'].dt.year == 2018]
df_2014_2021.loc[10294]['Story'] | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Detect languages and find missing stories in df_complete All stories in German. Some include text in English too. | list(df_complete['Story']
stories = list(df_complete['Story'])
languages_stories = []
missing_stories = [] # index of missing stories in LIST stories
for i, story in enumerate(stories):
try:
lan = detect(story)
except:
lan = np.nan
missing_stories.append(i)
languages_stories.append(l... | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
--- Scrape data | def scrape_links():
'''
Scrapes links of all the cases registered
'''
years = [x for x in range(2007, 2022)]
links_cases = []
titles_cases = []
for year in years:
path = f'https://berliner-register.de/chronik?field_datum_value%5Bvalue%5D%5Byear%5D={year}'
response = requests... | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Make dataframe | df_complete = pd.DataFrame(cases_dict)
df_complete['Date'] = pd.to_datetime(df_complete['Date']) # parse dates
# pickle df_complete
with open('df_complete.pickle', 'wb') as f:
pickle.dump(df_complete, f) | _____no_output_____ | MIT | final_project/Berliner_Register.ipynb | fserro/LGBT-violence-Berlin |
Altair ContinuedWe last looked at the US Employment dataset, and created some starter visualizations. This time, we'll be analyzing and visualizing the [palmerpenguins](https://github.com/allisonhorst/palmerpenguins) dataset, which is a great starter dataset! More information can be found by following the link (includ... | #!pip install palmerpenguins
import altair as alt
from palmerpenguins import load_penguins
penguins = load_penguins()
penguins.sample(5) | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Data ExplorationUsing the methods from the previous worksheet, answer the following questions about the palmerpenguins dataset. Question 1: Which species of penguins are represented in this dataset? | # Write your answer to question 1 here | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Question 2: On average, which species of penguin has the longest beak? | # Write your answer to question 2 here | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Question 3: Describe the relationship between flipper length and bill length. | # Write your answer to question 3 here | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Question 4: Create a scatterplot for flipper length vs bill length. Each species should be a different color. | # Write your answer to question 4 here | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Question 5: Compare and describe the distribution of flipper lengths across the different species. | # Write your answer to question 5 here | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
More Altair!Let's start off by visualizing the relationship between bill length and bill depth. Notice the use of `.interactive()` after we've defined the marks and channels. This allows the user to scroll and pan through the visualization -- since this is such a common request, Altair provides it by default! | alt.Chart(penguins).mark_point().encode(
x="bill_length_mm:Q",
y="bill_depth_mm:Q"
).interactive()
# Now let's color-code the species
species_color = alt.Color("species:N") # We can extract this out into a separate variable
alt.Chart(penguins).mark_point().encode(
x="bill_length_mm:Q",
y="bill_depth_mm... | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Other InteractionsWhat if you want to do more than just panning and zooming? Then you'll need to understand how Altair represents interactions. More information can be found [at the documentation here](https://altair-viz.github.io/user_guide/interactions.html). The next few examples are based on the documentation. Sel... | selection = alt.selection_interval() # Use a rectangular selection
species_color = alt.condition(selection, # Set the color to change depending on a the selection
alt.Color("species:N", legend=None),
alt.value("lightgray"))
# Create scatterplot of bill le... | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
A More Complicated ExampleWhat if you wanted to allow the viewer to click on a species to see all the corresponding points? Examine the code below while thinking about what the *selection* and *condition* are. | selection = alt.selection_multi(fields=['species']) # A different kind of selection!
species_color = alt.condition(selection, # Set the color to change depending on a the selection
alt.Color("species:N", legend=None),
alt.value("lightgray"))
# Create scat... | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Your Turn to PracticeLook through the above examples and documentation! **Make sure you read carefully through my code!** These will be good references. Practice 1: Visualize the relationship between flipper length and body mass. Allow the user to filter by species. | # Write your code for Practice 1 here. | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
Practice 2: Visualize the relationship between island and body mass. Choose appropriate marks, channels, and interactions! | # Write your code for Practice 2 here. | _____no_output_____ | MIT | art of data/topics/data viz/archive/altair_cont.ipynb | lee-edu/materials |
A notebook to test the calculation of the buuoyancy frequency as implemented in froude.py. | import matplotlib.pyplot as plt
import netCDF4 as nc
import froude
import os
import numpy as np
import datetime
%matplotlib inline | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Load some data to experiment with | path = '/data/nsoontie/MEOPAR/SalishSea/results/2Ddomain/3.6'
directory = 'base_aug'
file_part = 'SalishSea_1d_20030819_20030927_{}.nc'
dT = nc.Dataset(os.path.join(path,directory,file_part.format('grid_T')))
sal = dT.variables['vosaline'][:]
sal = np.ma.masked_values(sal,0)
deps = dT.variables['deptht'][:]
temp = dT.... | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Load the mesh_mask file for scale factors | mesh = nc.Dataset('/data/nsoontie/MEOPAR/2Ddomain/grid/mesh_mask.nc')
e3w = mesh.variables['e3w'][0,:,:,:] # NEMO uses e3w.
rho = froude.calculate_density(temp, sal) | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Calculate buoyancy frequency with froude module | reload(froude)
n2_f = froude.calculate_buoyancy_frequency(temp, sal, e3w, 1)
n2_f = np.ma.masked_values(n2_f,0) | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Plot n2_f to see that it makes sense. | yslice=5
fig, axs = plt.subplots(8,5,figsize=(20,10))
for t, ax in zip (np.arange(times.shape[0]), axs.flat):
ax.pcolor(np.arange(n2_f.shape[-1]),deps,n2_f[t,:,yslice,:],vmin=-0.01,vmax = 0.01)
ax.set_title(t)
ax.set_ylim([400,0]) | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Compare with NEMO's buoyancy frequency. | diff = n2-n2_f;
print np.ma.max(diff)
print np.ma.min(diff)
print np.ma.mean(diff)
ind = np.unravel_index(np.ma.argmax(diff), diff.shape)
ind
for t in np.arange(times.shape[0]):
max = np.ma.max(diff[t,...])
ind = np.unravel_index(np.ma.argmax(diff[t,...]), diff[t,:,:,:].shape)
print t, ind, max | 0 (4, 4, 1098) 0.0637975778828
1 (4, 4, 1098) 0.0608109813299
2 (4, 3, 1098) 0.0397740351603
3 (4, 6, 1098) 0.0209874000337
4 (5, 4, 1098) 0.00988855767693
5 (5, 3, 1098) 0.00900880743467
6 (5, 2, 1098) 0.00978058835956
7 (9, 7, 1098) 0.0110632234048
8 (9, 7, 1098) 0.0124031425429
9 (9, 6, 1098) 0.012225554126
10 (9, 7... | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
I think the major differences have to do with the vertical stretching of the grid due to vvl. This is largest at the right side of the domain. I'm not particularly interated in the buoyany frequency in that location, so can I neglec this? Probably. What do the differences look like elsewhere? | yslice=5
fig, axs = plt.subplots(8,5,figsize=(20,10))
for t, ax in zip (np.arange(times.shape[0]), axs.flat):
ax.pcolor(diff[t,:,yslice,:],vmin=-0.01,vmax = 0.01)
ax.set_title(t)
ax.set_ylim([40,0]) | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
How do these differences affect my Froude number calculations? | n2_f_slice= n2_f[:,:,yslice,:]
rho_slice = rho[:,:,yslice,:]
u_slice = U[:,:,yslice,:]
n2_slice= n2[:,:,yslice,:]
Fr_mys, cs, uvgs, dates = froude.froude_time_series(n2_f_slice,rho_slice,u_slice,
deps,depsU,times, time_origin)
Fr_NEMO, cs, uvgs, dates = froude.froud... | _____no_output_____ | Apache-2.0 | analysis/Testing Buoyancy Frequency.ipynb | SalishSeaCast/2d-domain |
Introduction to Artificial Intelligence - TP1 - April 11th 2018 --At the end of this session, you will be able to : - Generate PyRat Datasets for a supervised learning setting- Perform basic supervised learning tasks using sklearn- Apply supervised learning on PyRat datasets | # The tqdm package is useful to visualize progress with long computations.
# Install it using pip
import tqdm | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Part 1 - Generating PyRat datasets--First and foremost you need the latest version of PyRat. To do that, just clone the [official PyRat repository](https://github.com/vgripon/pyrat). Syntax is "git clone repo destinationdir" | ### TO DO : open a terminal tab / window and clone the repo. | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
You can now launch Pyrat Games. In the context of the AI course, we are going to simplify the rules of PyRat a bit.In fact, we are going to remove all walls and mud penalties. Also, we are not going to consider symmetric mazes anymore.As such, a default game would be obtained with the following parameters:python3 pyrat... | ### TO DO : open a terminal tab / window and launch the command to generate the games | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
To convert the games into numpy arrays, we will make use of a few functions that we define here. Feel try to modify it later to your own needs. | import numpy as np
import ast
import os
mazeHeight = 15
mazeWidth = 21
def convert_input(maze, mazeWidth, mazeHeight, piecesOfCheese):
im_size = (mazeWidth, mazeHeight)
canvas = np.zeros(im_size,dtype=np.int8)
for (x_cheese,y_cheese) in piecesOfCheese:
canvas[x_cheese,y_cheese] = 1
# For use ... | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Now we are ready to parse the "saves" folder in order to generate the data into a numpy array. **N.b. you don't have to run this cell if you want to just run through the provided correction of TP1, we provide a npz file with a saved dataset** |
games = list()
directory = "saves/"
for root, dirs, files in os.walk(directory):
for filename in tqdm.tqdm(files):
try:
if filename.startswith("."):
continue
game_params = process_file(directory+filename)
games.append(game_params)
except:
... | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
x and y are numpy array, feel free to save them to a .npz file as seen in TP0. | ### CELL TO BE COMPLETED
### CHECK THE SHAPES OF X AND Y
### SAVE X AND Y IN A NPZ FILE
print(x.shape,y.shape)
np.savez("dataset.npz",x=x,y=y) | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Part 2 - Basics of machine learning using sklearn-- sklearn is a very powerful package that implements most machine learning methods. sklearn also includes cross-validation procedures in order to prevent overfitting, many useful metrics and data manipulation techniques that enables very careful experimentations with ma... | from sklearn.datasets import make_blobs | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Use the function make_blobs to generate clouds of points with $d=2$, and visualize them using the function scatter from matplotlib.pyplot. You can generate as many samples as you want.You can generate several clouds of points using the argument centers. We recommend using random_state=0 so that your results are from th... | ### CELL TO BE COMPLETED - generate blobs
x_blobs,y_blobs = make_blobs(n_samples=2000,n_features=2,centers=4,random_state=0)
### CELL TO BE COMPLETED - plot
### Don't forget to import pyplot and use %matplotlib inline
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(x_blobs[:,0],x_blobs[:,1],c=y_b... | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
You can use the other arguments from make_blobs in order to change the variance of the blobs, or the coordinates of their center. You can also experiment in higher dimension, although it becomes difficult to visualize. sklearn has many other data generators, as well as ways to load standard datasets of various sizes. ... | from sklearn.model_selection import train_test_split
#### CELL TO BE COMPLETED
x_train, x_test, y_train, y_test = train_test_split(x_blobs,y_blobs,test_size=0.2,random_state=0) | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Check the shapes of the generated vectors | x_train.shape,x_test.shape,x_blobs.shape | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Let's use a K-Nearest Neighbor classifier to test whether we can classify this data. Create a classifier, train it using your training set and evaluate it by its accuracy on both the train and test sets. A k-nearest neighbor classifier (also known as KNN) is a method where for each object that you want to predict the... | from sklearn.neighbors import KNeighborsClassifier
k = 1
classifier = KNeighborsClassifier(n_neighbors=k,n_jobs=1)
### CELL TO BE COMPLETED - train the classifier and get the accuracy in both sets.
classifier.fit(x_train,y_train)
print("Accuracy on the training set {}%".format(classifier.score(x_train,y_train)*100))
p... | Accuracy on the training set 100.0%
Accuracy on the test set 91.0%
| MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Your classifier should have a train accuracy of 1, while the test accuracy should be high but not perfect.This is caused by the bias-variance trade-off. The 1NN classifier always has a bias of 0 (it perfectly classifies the training set) but it should have a high variance given that having one more example in the train... | train_acc = list()
test_acc = list() # list to add the test set accuracies
test_ks = range(1,25)# list containing values of k to be tested
# CELL TO BE COMPLETED - Train networks with varying k
for k in tqdm.tqdm(test_ks):
local_classifier = KNeighborsClassifier(n_neighbors=k)
local_classifier.fit(x_train,y_tr... | 100%|██████████| 24/24 [00:00<00:00, 57.20it/s]
| MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
With the classifier trained, bias-variance analysed, it is now time to look at other metrics based on your results. It is important to remember that accuracy is a key metric, but it is not the only metric you should be focusing on.We are going to be printing a [classification report](http://scikit-learn.org/stable/mo... | from sklearn.metrics import classification_report,confusion_matrix
y_pred_train = classifier.predict(x_train)
report = classification_report(y_true=y_train,y_pred=y_pred_train)
matrix = confusion_matrix(y_true=y_train,y_pred=y_pred_train)
print("Training Set:")
print(report)
print(matrix)
plt.matshow(matrix)
plt.colorb... | Test Set:
precision recall f1-score support
0 0.80 0.90 0.84 96
1 0.96 0.92 0.94 103
2 0.90 0.84 0.87 100
3 0.99 0.98 0.99 101
avg / total 0.91 0.91 0.91 ... | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Finally we are going to plot the decision boundaries from our model. For this you should use the function plot_boundaries given below. You can only do this if the tensor representing your data is two dimensional.This function will be testing our model with values ranging from the smallest x to the highest x and from th... | from matplotlib.colors import ListedColormap
def plot_boundaries(classifier,X,Y,h=0.2):
x0_min, x0_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x1_min, x1_max = X[:, 1].min() - 1, X[:, 1].max() + 1
x0, x1 = np.meshgrid(np.arange(x0_min, x0_max,h),
np.arange(x1_min, x1_max,h))
data... | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Part 3 - Application to PyRat Datasets--Now it is your turn, generate a pyrat dataset, load it in the notebook and evaluate a KNN classifier using sklearn In this corrected version of TP1, we load an example generated dataset | x = np.load("dataset_correction.npz")['x']
y = np.load("dataset_correction.npz")['y'] | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
First we check the shapes for our x and y that we defined before | x.shape,y.shape | _____no_output_____ | MIT | session2/Resolved TP1.ipynb | isival/IntroToAI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.