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 |
|---|---|---|---|---|---|
k大于63后,精度会急剧下降。 这是由于数据集中每个类只有50个实例。 因此,让我们通过将“ n_neighbors”的值限制为较小的值来进行深入研究。 | def hyperopt_train_test(params):
clf = KNeighborsClassifier(**params)
return cross_val_score(clf, X, y).mean()
space4knn = {
'n_neighbors': hp.choice('n_neighbors', range(1,50))
}
def f(params):
acc = hyperopt_train_test(params)
return {'loss': -acc, 'status': STATUS_OK}
trials = Trials()
best = ... | _____no_output_____ | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
上面的模型没有做任何预处理。所以我们来归一化和缩放特征,看看是否有帮助。用如下代码: | # 归一化和缩放特征
from sklearn.preprocessing import normalize, scale
iris = datasets.load_iris()
X = iris.data
y = iris.target
def hyperopt_train_test(params):
X_ = X[:]
if 'normalize' in params:
if params['normalize'] == 1:
X_ = normalize(X_)
del params['normalize']
if 'scale' in p... | 100%|█| 100/100 [00:02<00:00, 34.37it/s, best loss: -0.98000000
best: {'n_neighbors': 3, 'normalize': 1, 'scale': 0}
| Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
绘制参数 | parameters = ['n_neighbors', 'scale', 'normalize']
cols = len(parameters)
f, axes = plt.subplots(nrows=1, ncols=cols, figsize=(15,5))
cmap = plt.cm.jet
for i, val in enumerate(parameters):
xs = np.array([t['misc']['vals'][val] for t in trials.trials]).ravel()
ys = [-t['result']['loss'] for t in trials.trials]
... | 'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.
'c' argument looks like a single nume... | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
支持向量机(SVM)由于这是一个分类任务,我们将使用sklearn的SVC类。代码如下: | from sklearn.svm import SVC
def hyperopt_train_test(params):
X_ = X[:]
if 'normalize' in params:
if params['normalize'] == 1:
X_ = normalize(X_)
del params['normalize']
if 'scale' in params:
if params['scale'] == 1:
X_ = scale(X_)
del params['scale... | 100%|█| 100/100 [00:08<00:00, 12.02it/s, best loss: -0.98666666
best: {'C': 8.238774783515044, 'gamma': 1.1896015071446002, 'kernel': 3, 'normalize': 1, 'scale': 1}
| Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
同样,缩放和规范化也无济于事。 核函数的最佳选择是(线性核),最佳C值为1.4168540399911616,最佳gamma为15.04230279483486。 这组参数的分类精度为99.3%。 | parameters = ['C', 'kernel', 'gamma', 'scale', 'normalize']
cols = len(parameters)
f, axes = plt.subplots(nrows=1, ncols=cols, figsize=(20,5))
cmap = plt.cm.jet
for i, val in enumerate(parameters):
xs = np.array([t['misc']['vals'][val] for t in trials.trials]).ravel()
ys = [-t['result']['loss'] for t in trials.... | 'c' argument looks like a single numeric RGB or RGBA sequence, which should be avoided as value-mapping will have precedence in case its length matches with 'x' & 'y'. Please use a 2-D array with a single row if you really want to specify the same RGB or RGBA value for all points.
'c' argument looks like a single nume... | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
决策树我们将尝试只优化决策树的一些参数,码如下。 | from sklearn.tree import DecisionTreeClassifier
def hyperopt_train_test(params):
X_ = X[:]
if 'normalize' in params:
if params['normalize'] == 1:
X_ = normalize(X_)
del params['normalize']
if 'scale' in params:
if params['scale'] == 1:
X_ = scale(X_)
... | 100%|█| 100/100 [00:01<00:00, 54.98it/s, best loss: -0.97333333
best: {'criterion': 0, 'max_depth': 2, 'max_features': 3, 'normalize': 0, 'scale': 0}
| Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
Random Forests让我们看看 ensemble 的分类器 随机森林,它只是一组决策树的集合。 | from sklearn.ensemble import RandomForestClassifier
def hyperopt_train_test(params):
X_ = X[:]
if 'normalize' in params:
if params['normalize'] == 1:
X_ = normalize(X_)
del params['normalize']
if 'scale' in params:
if params['scale'] == 1:
X_ = scale(X_)
... | 100%|█| 100/100 [00:11<00:00, 8.92it/s, best loss: -0.97333333
best:
{'criterion': 1, 'max_depth': 14, 'max_features': 2, 'n_estimators': 0, 'normalize': 0, 'scale': 0}
| Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
同样的我们得到 97.3 % 的正确率 , 和decision tree 的结果一致. All Together Now一次自动调整一个模型的参数(例如,SVM或KNN)既有趣又有启发性,但如果一次调整所有模型参数并最终获得最佳模型更为有用。 这使我们能够一次比较所有模型和所有参数,从而为我们提供最佳模型。 | from sklearn.naive_bayes import BernoulliNB
def hyperopt_train_test(params):
t = params['type']
del params['type']
if t == 'naive_bayes':
clf = BernoulliNB(**params)
elif t == 'svm':
clf = SVC(**params)
elif t == 'dtree':
clf = DecisionTreeClassifier(**params)
elif t ==... | new best:
0.9333333333333333
using
knn
new best:
... | Apache-2.0 | notebooks/hyperopt_on_iris_data.ipynb | jianzhnie/AutoML-Tools |
Black-Scholes Algorithm Using Numba-dppy Sections- [Black Sholes algorithm](Black-Sholes-algorithm)- _Code:_ [Implementation of Black Scholes targeting CPU using Numba JIT](Implementation-of-Black-Scholes-targeting-CPU-using-Numba-JIT)- _Code:_ [Implementation of Black Scholes targeting GPU using Kernels](Implementat... | %%writefile lab/black_sholes_jit_cpu.py
# Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import dpctl
import base_bs_erf
import numba as nb
from math import log, sqrt, exp, erf
# blackscholes implemented as a parallel loop using numba.prange
@nb.njit(parallel=True, fastmath=True)
def black... | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Build and RunSelect the cell below and click run ▶ to compile and execute the code: | ! chmod 755 q; chmod 755 run_black_sholes_jit_cpu.sh; if [ -x "$(command -v qsub)" ]; then ./q run_black_sholes_jit_cpu.sh; else ./run_black_sholes_jit_cpu.sh; fi | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Implementation of Black Scholes targeting GPU using Numba JITIn the below example we introduce to a Naive Blacksholes implementation that targets a GPU using the Numba Jit where we calculate the blacksholes formula as described above.1. Inspect the code cell below and click run ▶ to save the code to a file.2. Next run... | %%writefile lab/black_sholes_jit_gpu.py
# Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import dpctl
import base_bs_erf_gpu
import numba as nb
from math import log, sqrt, exp, erf
# blackscholes implemented as a parallel loop using numba.prange
@nb.njit(parallel=True, fastmath=True)
def b... | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Build and RunSelect the cell below and click run ▶ to compile and execute the code: | ! chmod 755 q; chmod 755 run_black_sholes_jit_gpu.sh; if [ -x "$(command -v qsub)" ]; then ./q run_black_sholes_jit_gpu.sh; else ./run_black_sholes_jit_gpu.sh; fi | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Implementation of Black Scholes targeting GPU using Kernels Writing Explicit Kernels in numba-dppyWriting a SYCL kernel using the `@numba_dppy.kernel` decorator has similar syntax to writing OpenCL kernels. As such, the numba-dppy module provides similar indexing and other functions as OpenCL. The indexing functions s... | %%writefile lab/black_sholes_kernel.py
# Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import dpctl
import base_bs_erf_gpu
import numba_dppy
from math import log, sqrt, exp, erf
# blackscholes implemented using dppy.kernel
@numba_dppy.kernel(
access_types={"read_only": ["price", "stri... | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Build and RunSelect the cell below and click run ▶ to compile and execute the code: | ! chmod 755 q; chmod 755 run_black_sholes_kernel.sh; if [ -x "$(command -v qsub)" ]; then ./q run_black_sholes_kernel.sh; else ./run_black_sholes_kernel.sh; fi | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Implementation of Black Scholes targeting GPU using NumpyIn the following example, we can observe the Black Scholes NumPy implementation and we target the GPU using the NumPy approach.1. Inspect the code cell below and click run ▶ to save the code to a file.2. Next run ▶ the cell in the __Build and Run__ section below... | %%writefile lab/black_sholes_numpy_graph.py
# Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
# Copyright (C) 2017-2018 Intel Corporation
#
# SPDX-License-Identifier: MIT
import dpctl
import base_bs_erf_graph
import numba as nb
import numpy as np
from numpy import log, exp, sqrt
from math i... | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Build and RunSelect the cell below and click run ▶ to compile and execute the code: | ! chmod 755 q; chmod 755 run_black_sholes_numpy_graph.sh; if [ -x "$(command -v qsub)" ]; then ./q run_black_sholes_numpy_graph.sh; else ./run_black_sholes_numpy_graph.sh; fi | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Plot GPU ResultsThe algorithm below is detecting Calls and Puts verses Current price for a strike price in range 23 to 25 and plots the results in a graph as shown below. View the resultsSelect the cell below and click run ▶ to view the graph: | from matplotlib import pyplot as plt
import numpy as np
def read_dictionary(fn):
import pickle
# Load data (deserialize)
with open(fn, 'rb') as handle:
dictionary = pickle.load(handle)
return dictionary
resultsDict = read_dictionary('resultsDict.pkl')
limit = 10
call = resultsDict['call']
put... | _____no_output_____ | MIT | AI-and-Analytics/Jupyter/Numba_DPPY_Essentials_training/04_DPPY_Black_Sholes/DPPY_Black_Sholes.ipynb | krzeszew/oneAPI-samples |
Dataset: winequality-white.csv | # Read the csv file into a pandas DataFrame
white = pd.read_csv('./datasets/winequality-white.csv')
white.head()
# Assign the data to X and y
# Note: Sklearn requires a two-dimensional array of values
# so we use reshape to create this
X = white.alcohol.values.reshape(-1, 1)
y = white.quality.values.reshape(-1, 1)
pr... | _____no_output_____ | FTL | .ipynb_checkpoints/1-2-linear-regression-winequality-white-checkpoint.ipynb | hockeylori/FinalProject-Team8 |
Test | %matplotlib inline
import matplotlib.pyplot as plt
from boxplot import boxplot as bx
import numpy as np
| _____no_output_____ | MIT | code/test.ipynb | HurryZhao/boxplot |
Quality of data | # Integers
Integers = [np.random.randint(-3, 3, 500, dtype='l'),np.random.randint(-10, 10, 500, dtype='l')]
Float = np.random.random([2,500]).tolist()
fig,ax = plt.subplots(figsize=(10,10))
bx.boxplot(ax,Integers)
fig,ax = plt.subplots(figsize=(10,10))
bx.info_boxplot(ax,Integers)
fig,ax = plt.subplots(figsize=(10,10)... | [0.36623335, 0.7324667]
| MIT | code/test.ipynb | HurryZhao/boxplot |
Real dataset | import pandas as pd
data = pd.read_csv('/Users/hurryzhao/boxplot/results_merged.csv')
data.head()
t_d1 = data.commits[data.last_updated=='2017-08-28']
t_d2 = data.commits[data.last_updated=='2017-08-26']
t_d3 = data.commits[data.last_updated=='2017-08-24']
t_d4 = data.commits[data.last_updated=='2017-08-22']
t_d5 = da... | [333.3333333319238, 666.6666666680761, 999.9999999999999, 1333.3333333319238, 1666.6666666680758]
| MIT | code/test.ipynb | HurryZhao/boxplot |
Robustness | data=[['1','1','2','2','3','4'],['1','1','2','2','3','4']]
fig,ax = plt.subplots(figsize=(10,10))
bx.boxplot(ax,data,outlier_facecolor='white',outlier_edgecolor='r',outlier=False) | Wrong data type, please input a list of numerical list
| MIT | code/test.ipynb | HurryZhao/boxplot |
TSG097 - Get BDC stateful sets (Kubernetes)===========================================Description-----------Steps----- Common functionsDefine helper functions used in this notebook. | # Define `run` function for transient fault handling, suggestions on error, and scrolling updates on Windows
import sys
import os
import re
import json
import platform
import shlex
import shutil
import datetime
from subprocess import Popen, PIPE
from IPython.display import Markdown
retry_hints = {} # Output in stderr... | _____no_output_____ | MIT | Big-Data-Clusters/CU4/Public/content/monitor-k8s/tsg097-get-statefulsets.ipynb | gantz-at-incomm/tigertoolbox |
Get the Kubernetes namespace for the big data clusterGet the namespace of the Big Data Cluster use the kubectl command lineinterface .**NOTE:**If there is more than one Big Data Cluster in the target Kubernetescluster, then either:- set \[0\] to the correct value for the big data cluster.- set the environment vari... | # Place Kubernetes namespace name for BDC into 'namespace' variable
if "AZDATA_NAMESPACE" in os.environ:
namespace = os.environ["AZDATA_NAMESPACE"]
else:
try:
namespace = run(f'kubectl get namespace --selector=MSSQL_CLUSTER -o jsonpath={{.items[0].metadata.name}}', return_output=True)
except:
... | _____no_output_____ | MIT | Big-Data-Clusters/CU4/Public/content/monitor-k8s/tsg097-get-statefulsets.ipynb | gantz-at-incomm/tigertoolbox |
Run kubectl to display the Stateful sets | run(f"kubectl get statefulset -n {namespace} -o wide")
print('Notebook execution complete.') | _____no_output_____ | MIT | Big-Data-Clusters/CU4/Public/content/monitor-k8s/tsg097-get-statefulsets.ipynb | gantz-at-incomm/tigertoolbox |
Trajectory equations: | %matplotlib inline
import matplotlib.pyplot as plt
from sympy import *
init_printing()
Bx, By, Bz, B = symbols("B_x, B_y, B_z, B")
x, y, z = symbols("x, y, z" )
x_0, y_0, z_0 = symbols("x_0, y_0, z_0")
vx, vy, vz, v = symbols("v_x, v_y, v_z, v")
vx_0, vy_0, vz_0 = symbols("v_x0, v_y0, v_z0")
t = symbols("t")
q, m = sym... | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
The equation of motion:$$\begin{gather*} m \frac{d^2 \vec{r} }{dt^2} = \frac{q}{c} [ \vec{v} \vec{B} ] \end{gather*}$$ For the case of a uniform magnetic field along the $z$-axis: $$ \vec{B} = B_z = B, \quad B_x = 0, \quad B_y = 0 $$ In Cortesian coordinates: | eq_x = Eq( Derivative(x(t), t, 2), q / c / m * Bz * Derivative(y(t),t) )
eq_y = Eq( Derivative(y(t), t, 2), - q / c / m * Bz * Derivative(x(t),t) )
eq_z = Eq( Derivative(z(t), t, 2), 0 )
display( eq_x, eq_y, eq_z ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
Motion is uniform along the $z$-axis: | z_eq = dsolve( eq_z, z(t) )
vz_eq = Eq( z_eq.lhs.diff(t), z_eq.rhs.diff(t) )
display( z_eq, vz_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
The constants of integration can be found from the initial conditions $z(0) = z_0$ and $v_z(0) = v_{z0}$: | c1_c2_system = []
initial_cond_subs = [(t, 0), (z(0), z_0), (diff(z(t),t).subs(t,0), vz_0) ]
c1_c2_system.append( z_eq.subs( initial_cond_subs ) )
c1_c2_system.append( vz_eq.subs( initial_cond_subs ) )
c1, c2 = symbols("C1, C2")
c1_c2 = solve( c1_c2_system, [c1, c2] )
c1_c2 | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
So that | z_sol = z_eq.subs( c1_c2 )
vz_sol = vz_eq.subs( c1_c2 ).subs( [( diff(z(t),t), vz(t) ) ] )
display( z_sol, vz_sol ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
For some reason I have not been able to solve the system of differential equations for $x$ and $y$ directlywith Sympy's `dsolve` function: | #dsolve( [eq_x, eq_y], [x(t),y(t)] ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
It is necessary to resort to the manual solution. The method is to differentiate one of them over time and substitute the other. This will result in oscillator-type second-order equations for $v_y$ and $v_x$. Their solution is known. Integrating one more time, it is possible to obtain laws of motion $x(t)$ and $y(t)$. | v_subs = [ (Derivative(x(t),t), vx(t)), (Derivative(y(t),t), vy(t)) ]
eq_vx = eq_x.subs( v_subs )
eq_vy = eq_y.subs( v_subs )
display( eq_vx, eq_vy )
eq_d2t_vx = Eq( diff(eq_vx.lhs,t), diff(eq_vx.rhs,t))
eq_d2t_vx = eq_d2t_vx.subs( [(eq_vy.lhs, eq_vy.rhs)] )
display( eq_d2t_vx ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
The solution of the last equation is | C1, C2, Omega = symbols( "C1, C2, Omega" )
vx_eq = Eq( vx(t), C1 * cos( Omega * t ) + C2 * sin( Omega * t ))
display( vx_eq )
omega_eq = Eq( Omega, Bz * q / c / m )
display( omega_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
where $\Omega$ is a cyclotron frequency. | display( vx_eq )
vy_eq = Eq( vy(t), solve( Eq( diff(vx_eq.rhs,t), eq_vx.rhs ), ( vy(t) ) )[0] )
vy_eq = vy_eq.subs( [(Omega*c*m / Bz / q, omega_eq.rhs * c * m / Bz / q)]).simplify()
display( vy_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
For initial conditions $v_x(0) = v_{x0}, v_y(0) = v_{y0}$: | initial_cond_subs = [(t,0), (vx(0), vx_0), (vy(0), vy_0) ]
vx0_eq = vx_eq.subs( initial_cond_subs )
vy0_eq = vy_eq.subs( initial_cond_subs )
display( vx0_eq, vy0_eq )
c1_c2 = solve( [vx0_eq, vy0_eq] )
c1_c2_subs = [ ("C1", c1_c2[c1]), ("C2", c1_c2[c2]) ]
vx_eq = vx_eq.subs( c1_c2_subs )
vy_eq = vy_eq.subs( c1_c2_subs ... | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
These equations can be integrated to obtain the laws of motion: | x_eq = vx_eq.subs( vx(t), diff(x(t),t))
x_eq = dsolve( x_eq )
y_eq = vy_eq.subs( vy(t), diff(y(t),t))
y_eq = dsolve( y_eq ).subs( C1, C2 )
display( x_eq, y_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
For nonzero $\Omega$: | x_eq = x_eq.subs( [(Omega, 123)] ).subs( [(123, Omega)] ).subs( [(Rational(1,123), 1/Omega)] )
y_eq = y_eq.subs( [(Omega, 123)] ).subs( [(123, Omega)] ).subs( [(Rational(1,123), 1/Omega)] )
display( x_eq, y_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
For initial conditions $x(0) = x_0, y(0) = y_0$: | initial_cond_subs = [(t,0), (x(0), x_0), (y(0), y_0) ]
x0_eq = x_eq.subs( initial_cond_subs )
y0_eq = y_eq.subs( initial_cond_subs )
display( x0_eq, y0_eq )
c1_c2 = solve( [x0_eq, y0_eq] )
c1_c2_subs = [ ("C1", c1_c2[0][c1]), ("C2", c1_c2[0][c2]) ]
x_eq = x_eq.subs( c1_c2_subs )
y_eq = y_eq.subs( c1_c2_subs )
display(... | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
Finally | display( x_eq, y_eq, z_sol )
display( vx_eq, vy_eq, vz_sol )
display( omega_eq ) | _____no_output_____ | MIT | examples/single_particle_in_magnetic_field/Single Particle in Uniform Magnetic Field.ipynb | tnakaicode/ChargedPaticle-LowEnergy |
人力规划等级:高级 目的和先决条件此模型是人员编制问题的一个示例。在人员编制计划问题中,必须在招聘,培训,裁员(裁员)和安排工时方面做出选择。人员配备问题在制造业和服务业广泛存在。 What You Will LearnIn this example, we will model and solve a manpower planning problem. We have three types of workers with different skills levels. For each year in the planning horizon, the forecasted number of required worke... | import gurobipy as gp
import numpy as np
import pandas as pd
from gurobipy import GRB
# tested with Python 3.7.0 & Gurobi 9.0 | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Input DataWe define all the input data of the model. | # Parameters
years = [1, 2, 3]
skills = ['s1', 's2', 's3']
curr_workforce = {'s1': 2000, 's2': 1500, 's3': 1000}
demand = {
(1, 's1'): 1000,
(1, 's2'): 1400,
(1, 's3'): 1000,
(2, 's1'): 500,
(2, 's2'): 2000,
(2, 's3'): 1500,
(3, 's1'): 0,
(3, 's2'): 2500,
(3, 's3'): 2000
}
rookie_a... | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Model DeploymentWe create a model and the variables. For each of the three skill levels and for each year, we will create variables for the number of workers that get recruited, transferred into part-time work, are available as workers, are redundant, or are overmanned. For each pair of skill levels and each year, we ... | manpower = gp.Model('Manpower planning')
hire = manpower.addVars(years, skills, ub=max_hiring, name="Hire")
part_time = manpower.addVars(years, skills, ub=max_parttime,
name="Part_time")
workforce = manpower.addVars(years, skills, name="Available")
layoff = manpower.addVars(years, skills, nam... | Using license file c:\gurobi\gurobi.lic
Set parameter TokenServer to value SANTOS-SURFACE-
| Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Next, we insert the constraints. The balance constraints ensure that per skill level and per year the workers who are currently required (LaborForce) and the people who get laid off, and the people who get retrained to the current level, minus the people who get retrained from the current level to a different skill, eq... | #1.1 & 1.2 Balance
Balance = manpower.addConstrs(
(workforce[year, level] == (1-veteran_attrition[level])*(curr_workforce[level] if year == 1 else workforce[year-1, level])
+ (1-rookie_attrition[level])*hire[year, level] + gp.quicksum((1- veteran_attrition[level])* train[year, level2, level]
... | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The Unskilled training constraints force that per year only 200 workers can be retrained from Unskilled to Semi-skilled due to capacity limitations. Also, no one can be trained in one year from Unskilled to Skilled. | #2.1 & 2.2 Unskilled training
UnskilledTrain1 = manpower.addConstrs((train[year, 's1', 's2'] <= max_train_unskilled for year in years), "Unskilled_training1")
UnskilledTrain2 = manpower.addConstrs((train[year, 's1', 's3'] == 0 for year in years), "Unskilled_training2") | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The Semi-skilled training states that the retraining of Semi-skilled workers to skilled workers is limited to no more than one quarter of the skilled labor force at this time. This is due to capacity limitations. | #3. Semi-skilled training
SemiskilledTrain = manpower.addConstrs((train[year,'s2', 's3'] <= max_train_semiskilled * workforce[year,'s3'] for year in years), "Semiskilled_training") | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The overmanning constraints ensure that the total overmanning over all skill levels in one year is no more than 150. | #4. Overmanning
Overmanning = manpower.addConstrs((excess.sum(year, '*') <= max_overmanning for year in years), "Overmanning") | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The demand constraints ensure that the number of workers of each level and year equals the required number of workers plus the Overmanned workers and the number of workers who are working part-time. | #5. Demand
Demand = manpower.addConstrs((workforce[year, level] ==
demand[year,level] + excess[year, level] + parttime_cap * part_time[year, level]
for year in years for level in skills), "Requirements") | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The first objective is to minimize the total number of laid off workers. This can be stated as: | #0.1 Objective Function: Minimize layoffs
obj1 = layoff.sum()
manpower.setObjective(obj1, GRB.MINIMIZE) | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
The second alternative objective is to minimize the total cost of all employed workers and costs for retraining:```obj2 = quicksum((training_cost[level]*train[year, level, skills[skills.index(level)+1]] if level < 's3' else 0) + layoff_cost[level]*layoff[year, level] + parttime_cost[level]... | manpower.optimize() | Gurobi Optimizer version 9.0.0 build v9.0.0rc2 (win64)
Optimize a model with 30 rows, 72 columns and 117 nonzeros
Model fingerprint: 0x06ec5b66
Coefficient statistics:
Matrix range [3e-01, 1e+00]
Objective range [1e+00, 1e+00]
Bounds range [5e+01, 8e+02]
RHS range [2e+02, 3e+03]
Presolve removed... | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
AnalysisThe minimum number of layoffs is 841.80. The optimal policies to achieve this minimum number of layoffs are given below. Hiring PlanThis plan determines the number of new workers to hire at each year of the planning horizon (rows) and each skill level (columns). For example, at year 2 we are going to hire 649.... | rows = years.copy()
columns = skills.copy()
hire_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for year, level in hire.keys():
if (abs(hire[year, level].x) > 1e-6):
hire_plan.loc[year, level] = np.round(hire[year, level].x, 1)
hire_plan | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Training and Demotions PlanThis plan defines the number of workers to promote by training (or demote) at each year of the planning horizon. For example, in year 1 we are going to demote 168.4 skilled (s3) workers to the level of semi-skilled (s2). | rows = years.copy()
columns = ['{0} to {1}'.format(level1, level2) for level1 in skills for level2 in skills if level1 != level2]
train_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for year, level1, level2 in train.keys():
col = '{0} to {1}'.format(level1, level2)
if (abs(train[year, level1, leve... | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Layoffs PlanThis plan determines the number of workers to layoff of each skill level at each year of the planning horizon. For example, we are going to layoff 232.5 Unskilled workers in year 3. | rows = years.copy()
columns = skills.copy()
layoff_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for year, level in layoff.keys():
if (abs(layoff[year, level].x) > 1e-6):
layoff_plan.loc[year, level] = np.round(layoff[year, level].x, 1)
layoff_plan | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Part-time PlanThis plan defines the number of part-time workers of each skill level working at each year of the planning horizon. For example, in year 1, we have 50 part-time skilled workers. | rows = years.copy()
columns = skills.copy()
parttime_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for year, level in part_time.keys():
if (abs(part_time[year, level].x) > 1e-6):
parttime_plan.loc[year, level] = np.round(part_time[year, level].x, 1)
parttime_plan | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
Overmanning PlanThis plan determines the number of excess workers of each skill level working at each year of the planning horizon. For example, we have 150 Unskilled excess workers in year 3. | rows = years.copy()
columns = skills.copy()
excess_plan = pd.DataFrame(columns=columns, index=rows, data=0.0)
for year, level in excess.keys():
if (abs(excess[year, level].x) > 1e-6):
excess_plan.loc[year, level] = np.round(excess[year, level].x, 1)
excess_plan | _____no_output_____ | Apache-2.0 | documents/Advanced/ManpowerPlanning/manpower_planning.ipynb | biancaitian/gurobi-official-examples |
1. 基础回归 1.1 线性回归 1.1.1 sklearn.linear_model.LinearRegression https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.htmlsklearn.linear_model.LinearRegression | X_data, y_data = load_linear_data(point_count=500, max_=10, w=3.2412, b=-5.2941, random_state=10834)
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, random_state=19332)
rgs = LinearRegression(fit_intercept=True, normalize=False, copy_X=True, n_jobs=None)
rgs.fit(X_train, y_train)
rgs.coef_, rgs.int... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
正规化Normalizer 每个样本求范数,再用每个特征除以范数 | norm = Normalizer(norm="l2", copy=True)
X_train_norm = norm.fit_transform(X_train)
X_test_norm = norm.transform(X_test)
rgs = LinearRegression()
rgs.fit(X_train_norm, y_train)
rgs.coef_, rgs.intercept_
rgs.score(X_test_norm, y_test)
X_train_norm[:10], X_test_norm[:10]
X_train[:5]
rgs = LinearRegression(fit_intercept=Tr... | 376 µs ± 35.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
| MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
1.1.2 sklearn.linear_model.SGDRegressor https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.htmlsklearn.linear_model.SGDRegressor | X_data, y_data = load_linear_data(point_count=500, max_=10, w=3.2412, b=-5.2941, random_state=10834)
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, random_state=19332)
rgs = SGDRegressor(random_state=10190)
rgs.fit(X_train, y_train)
rgs.score(X_test, y_test) | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
标准化StandardScaler https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.htmlsklearn.preprocessing.StandardScaler z = (x - u) / s, u是均值, s是标准差 | scaler = StandardScaler(copy=True, with_mean=True, with_std=True)
X_train_scaler = scaler.fit_transform(X_train)
X_test_scaler = scaler.transform(X_test)
scaler.mean_, scaler.scale_
rgs = SGDRegressor(
loss='squared_loss', # ‘squared_loss’, ‘huber’, ‘epsilon_insensitive’, or ‘squared_epsilon_insensitive’
penalt... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
1.2 多项式回归 | def load_data_from_func(func=lambda X_data: 0.1383 * np.square(X_data) - 1.2193 * X_data + 2.4096,
x_min=0, x_max=10, n_samples=500, loc=0, scale=1, random_state=None):
if random_state is not None and isinstance(random_state, int):
np.random.seed(random_state)
x = np.random.unifo... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.htmlsklearn.preprocessing.PolynomialFeatures/ | X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, random_state=10319)
poly = PolynomialFeatures() # [1, a, b, a^2, ab, b^2]
X_train_poly = poly.fit_transform(X_train)
X_test_poly = poly.transform(X_test)
X_train_poly.shape
rgs = LinearRegression()
rgs.fit(X_train_poly, y_train)
rgs.score(X_test_poly,... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
2. 加利福尼亚房价数据集 | df = fetch_california_housing(data_home="./data", as_frame=True)
X_data = df['data']
X_data.describe()
X_train, X_test, y_train, y_test = train_test_split(X_data, df.target, random_state=1, shuffle=True) | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
2.1 线性回归 | rgs = LinearRegression()
rgs.fit(X_train, y_train)
rgs.score(X_test, y_test)
scaler = StandardScaler()
X_train_scaler = scaler.fit_transform(X_train)
X_test_scaler = scaler.transform(X_test)
rgs = LinearRegression()
rgs.fit(X_train_scaler, y_train)
rgs.score(X_test_scaler, y_test) | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
2.2 岭回归 https://scikit-learn.org/stable/modules/linear_model.htmlridge-regression-and-classification https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.htmlsklearn.linear_model.Ridge | rgs = Ridge(alpha=1.0, solver="auto")
rgs.fit(X_train, y_train)
rgs.score(X_test, y_test)
rgs.coef_ | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeCV.htmlsklearn.linear_model.RidgeCV 2.2.1 交叉验证 | rgs = RidgeCV(
alphas=(0.001, 0.01, 0.1, 1.0, 10.0),
fit_intercept=True,
normalize= False,
scoring=None, # 如果为None,则当cv为'auto'或为None时为负均方误差,否则为r2得分。scorer(estimator, X, y)
cv=None, # int, cross-validation generator or an iterable, default=None
gcv_mode='auto', # {‘auto’, ‘svd’, eigen’}, default=... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
2.3 索套回归 https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.htmlsklearn.linear_model.Lasso https://scikit-learn.org/stable/modules/linear_model.htmllasso | rgs = Lasso()
rgs.fit(X_train, y_train)
rgs.score(X_test, y_test)
rgs.coef_ | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
2.4 多项式回归 https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.PolynomialFeatures.html?highlight=polynomialfeaturessklearn.preprocessing.PolynomialFeatures | poly = PolynomialFeatures(degree=2, interaction_only=False, include_bias=True)
X_train_poly = poly.fit_transform(X_train) # [1, a, b, a^2, ab, b^2]
X_train_poly.shape
poly.get_feature_names()
X_test_poly = poly.transform(X_test)
rgs = LinearRegression()
rgs.fit(X_train_poly, y_train)
rgs.score(X_test_poly, y_test)
pol... | _____no_output_____ | MIT | 02.2.LinearRegression-sklearn.ipynb | LossJ/Statistical-Machine-Learning |
Local Time | hdr['LOCTIME'] #local time at start of exposure in header
images_time = []
for i in range(len(images)):
im,hdr = fits.getdata(images[i],header=True) #reading the fits image (data + header)
images_time.append(hdr['LOCTIME'])
update_progress((i+1.)/len(images))
print images_time #our local time series | ['22:29:57', '22:32:14', '22:34:31', '22:36:48', '22:39:05', '22:41:22', '22:43:39', '22:45:57', '22:48:14', '22:50:31', '22:52:48', '22:55:06', '22:57:23', '22:59:40', '23:01:57', '23:04:14', '23:06:31', '23:08:48', '23:11:05', '23:13:23', '23:15:40', '23:17:57', '23:20:14', '23:22:31', '23:24:48', '23:27:05', '23:29:... | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
FITS Time | fits_time = []
for i in range(len(images)):
im,hdr = fits.getdata(images[i],header=True) #reading the fits image (data + header)
fits_time.append(hdr['DATE'])
update_progress((i+1.)/len(images))
print fits_time | ['2016-02-08T17:01:06', '2016-02-08T17:01:07', '2016-02-08T17:01:07', '2016-02-08T17:01:07', '2016-02-08T17:01:08', '2016-02-08T17:01:09', '2016-02-08T17:01:10', '2016-02-08T17:01:10', '2016-02-08T17:01:10', '2016-02-08T17:01:11', '2016-02-08T17:01:11', '2016-02-08T17:01:12', '2016-02-08T17:01:12', '2016-02-08T17:01:14... | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Observatory (location) | #geting the observatory
im,hdr = fits.getdata(images[0],header=True) #reading the fits image (data + header)
observatory_loc = hdr['OBSERVAT']
print observatory_loc | mtbigelow
| CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Obtain UT using local time and observatory | #time formats
print list(Time.FORMATS)
#Let's using fits time
teste = Time(fits_time[0],format=u'fits')
teste
teste.jd #convert my object test in fits date to julian date
#Let's make to all time series
serie = np.zeros(len(fits_time))
for i in range(len(fits_time)):
serie[i] = Time(fits_time[i],format=u'fits').jd
s... | _____no_output_____ | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Error 404: Date don't found!Yes, and I know why! THe date in abxo2b*.fits images are the date from when it were created. Because of that, we need to extract the date from original images! | os.chdir('../')
images = glob.glob('xo2b*.fits')
os.chdir(save_path)
print images
fits_time = []
os.chdir(data_path)
for i in range(len(images)):
im,hdr = fits.getdata(images[i],header=True) #reading the fits image (data + header)
fits_time.append(hdr['DATE'])
update_progress((i+1.)/len(images))
os.chdir(sa... | _____no_output_____ | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Working with date in header following Kyle's subroutine stcoox.cl in ExoDRPL | import yaml
file = yaml.load(open('C:/Users/walte/MEGA/work/codes/iraf_task/input_path.yaml'))
RA,DEC, epoch = file['RA'],file['DEC'],file['epoch']
print RA,DEC,epoch
hdr['DATE-OBS'], hdr['UT']
local_time = Time(hdr['DATE-OBS']+'T'+hdr['ut'],format='isot')
print local_time.jd
teste_loc_time = Time('2012-12-09'+'T'+hd... | 0.000370370224118
2456271.73
| CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Local Time to sideral time | local_time = Time(hdr['DATE-OBS']+'T'+hdr['Time-obs'],format='isot',scale='utc')
time_sd = local_time.sidereal_time('apparent',longitude=file['lon-obs'])#with precession and nutation
print time_sd
time_sd.T.hms[0],time_sd.T.hms[1],time_sd.T.hms[2]
local_time.sidereal_time('mean',longitude=file['lon-obs']) #with precess... | _____no_output_____ | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
Change degrees to hours... | from astropy.coordinates import SkyCoord
from astropy import units as unit
from astropy.coordinates import Angle
RA = Angle(file['RA']+file['u.RA'])
DEC = Angle(file['DEC']+file['u.DEC'])
coordenadas = SkyCoord(RA,DEC,frame='fk5')
coordenadas
coordenadas.ra.hour, coordenadas.dec.deg,coordenadas.equinox,coordenadas.equi... | _____no_output_____ | CC-BY-4.0 | development/Obtain Universal Time UT using astropy.ipynb | waltersmartinsf/iraf_task |
**This notebook is an exercise in the [Geospatial Analysis](https://www.kaggle.com/learn/geospatial-analysis) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/interactive-maps).**--- IntroductionYou are an urban safety planner in Japan, and you are analyzing which areas of Japa... | import pandas as pd
import geopandas as gpd
import folium
from folium import Choropleth
from folium.plugins import HeatMap
from learntools.core import binder
binder.bind(globals())
from learntools.geospatial.ex3 import * | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
We define a function `embed_map()` for displaying interactive maps. It accepts two arguments: the variable containing the map, and the name of the HTML file where the map will be saved.This function ensures that the maps are visible [in all web browsers](https://github.com/python-visualization/folium/issues/812). | def embed_map(m, file_name):
from IPython.display import IFrame
m.save(file_name)
return IFrame(file_name, width='100%', height='500px') | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Exercises 1) Do earthquakes coincide with plate boundaries?Run the code cell below to create a DataFrame `plate_boundaries` that shows global plate boundaries. The "coordinates" column is a list of (latitude, longitude) locations along the boundaries. | plate_boundaries = gpd.read_file("../input/geospatial-learn-course-data/Plate_Boundaries/Plate_Boundaries/Plate_Boundaries.shp")
plate_boundaries['coordinates'] = plate_boundaries.apply(lambda x: [(b,a) for (a,b) in list(x.geometry.coords)], axis='columns')
plate_boundaries.drop('geometry', axis=1, inplace=True)
plate... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Next, run the code cell below without changes to load the historical earthquake data into a DataFrame `earthquakes`. | # Load the data and print the first 5 rows
earthquakes = pd.read_csv("../input/geospatial-learn-course-data/earthquakes1970-2014.csv", parse_dates=["DateTime"])
earthquakes.head() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
The code cell below visualizes the plate boundaries on a map. Use all of the earthquake data to add a heatmap to the same map, to determine whether earthquakes coincide with plate boundaries. | # Create a base map with plate boundaries
m_1 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_1)
# Your code here: Add a heatmap to the map
HeatMap(data=ea... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
So, given the map above, do earthquakes coincide with plate boundaries? | # View the solution (Run this code cell to receive credit!)
q_1.b.solution() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
2) Is there a relationship between earthquake depth and proximity to a plate boundary in Japan?You recently read that the depth of earthquakes tells us [important information](https://www.usgs.gov/faqs/what-depth-do-earthquakes-occur-what-significance-depth?qt-news_science_products=0qt-news_science_products) about the... | # Create a base map with plate boundaries
m_2 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_2)
# Your code here: Add a map to visualize earthquake de... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Can you detect a relationship between proximity to a plate boundary and earthquake depth? Does this pattern hold globally? In Japan? | # View the solution (Run this code cell to receive credit!)
q_2.b.solution() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
3) Which prefectures have high population density?Run the next code cell (without changes) to create a GeoDataFrame `prefectures` that contains the geographical boundaries of Japanese prefectures. | # GeoDataFrame with prefecture boundaries
prefectures = gpd.read_file("../input/geospatial-learn-course-data/japan-prefecture-boundaries/japan-prefecture-boundaries/japan-prefecture-boundaries.shp")
prefectures.set_index('prefecture', inplace=True)
prefectures.head() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
The next code cell creates a DataFrame `stats` containing the population, area (in square kilometers), and population density (per square kilometer) for each Japanese prefecture. Run the code cell without changes. | # DataFrame containing population of each prefecture
population = pd.read_csv("../input/geospatial-learn-course-data/japan-prefecture-population.csv")
population.set_index('prefecture', inplace=True)
# Calculate area (in square kilometers) of each prefecture
area_sqkm = pd.Series(prefectures.geometry.to_crs(epsg=32654... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Use the next code cell to create a choropleth map to visualize population density. | # Create a base map
m_3 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
# Your code here: create a choropleth map to visualize population density
Choropleth(geo_data=prefectures['geometry'].__geo_interface__,
data=stats['density'],
key_on="feature.id",
fill_co... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Which three prefectures have relatively higher density than the others? Are they spread throughout the country, or all located in roughly the same geographical region? (*If you're unfamiliar with Japanese geography, you might find [this map](https://en.wikipedia.org/wiki/Prefectures_of_Japan) useful to answer the que... | # View the solution (Run this code cell to receive credit!)
q_3.b.solution() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
4) Which high-density prefecture is prone to high-magnitude earthquakes?Create a map to suggest one prefecture that might benefit from earthquake reinforcement. Your map should visualize both density and earthquake magnitude. | # Create a base map
m_4 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
# Your code here: create a map
def color_producer(magnitude):
if magnitude > 6.5:
return 'red'
else:
return 'green'
Choropleth(
geo_data=prefectures['geometry'].__geo_interface__,
data=stats[... | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Which prefecture do you recommend for extra earthquake reinforcement? | # View the solution (Run this code cell to receive credit!)
q_4.b.solution() | _____no_output_____ | MIT | course/Geospatial Analysis/exercise-interactive-maps.ipynb | furyhawk/kaggle_practice |
Classification with Neural Network for Yoga poses detection Import Dependencies | import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from sklearn.met... | _____no_output_____ | Unlicense | _Project_Analysis/Neural_Network_model_training.ipynb | sijal001/Yoga_Pose_Detection |
Getting the data (images) and labels | # Data path
train_dir = 'pose_recognition_data/dataset'
# Getting the folders name to be able to labelize the data
Name=[]
for file in os.listdir(train_dir):
Name+=[file]
print(Name)
print(len(Name))
N=[]
for i in range(len(Name)):
N+=[i]
normal_mapping=dict(zip(Name,N))
reverse_mapping=dict(zip(N,Name)... | 0.27466666666666667
| Unlicense | _Project_Analysis/Neural_Network_model_training.ipynb | sijal001/Yoga_Pose_Detection |
TVAE Model===========In this guide we will go through a series of steps that will let youdiscover functionalities of the `TVAE` model, including how to:- Create an instance of `TVAE`.- Fit the instance to your data.- Generate synthetic versions of your data.- Use `TVAE` to anonymize PII information.- Specify ... | from sdv.demo import load_tabular_demo
data = load_tabular_demo('student_placements')
data.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
As you can see, this table contains information about students whichincludes, among other things:- Their id and gender- Their grades and specializations- Their work experience- The salary that they were offered- The duration and dates of their placementYou will notice that there is data with the following cha... | from sdv.tabular import TVAE
model = TVAE()
model.fit(data) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
**Note**Notice that the model `fitting` process took care of transforming thedifferent fields using the appropriate [Reversible DataTransforms](http://github.com/sdv-dev/RDT) to ensure that the data has aformat that the underlying TVAESynthesizer class can handle. Generate synthetic data from the modelOnce the modeling... | new_data = model.sample(num_rows=200) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
This will return a table identical to the one which the model was fittedon, but filled with new data which resembles the original one. | new_data.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
**Note**There are a number of other parameters in this method that you can use tooptimize the process of generating synthetic data. Use ``output_file_path``to directly write results to a CSV file, ``batch_size`` to break up samplinginto smaller pieces & track their progress and ``randomize_samples`` todetermine whether... | model.save('my_model.pkl') | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
This will have created a file called `my_model.pkl` in the samedirectory in which you are running SDV.**Important**If you inspect the generated file you will notice that its size is muchsmaller than the size of the data that you used to generate it. This isbecause the serialized model contains **no information about th... | loaded = TVAE.load('my_model.pkl')
new_data = loaded.sample(num_rows=200) | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
**Warning**Notice that the system where the model is loaded needs to also have`sdv` and `tvae` installed, otherwise it will not be able to load themodel and use it. Specifying the Primary Key of the tableOne of the first things that you may have noticed when looking at the demodata is that there is a `student_id` colum... | data.student_id.value_counts().max() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
However, if we look at the synthetic data that we generated, we observethat there are some values that appear more than once: | new_data[new_data.student_id == new_data.student_id.value_counts().index[0]] | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
This happens because the model was not notified at any point about thefact that the `student_id` had to be unique, so when it generates newdata it will provoke collisions sooner or later. In order to solve this,we can pass the argument `primary_key` to our model when we create it,indicating the name of the column that ... | model = TVAE(
primary_key='student_id'
)
model.fit(data)
new_data = model.sample(200)
new_data.head() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
As a result, the model will learn that this column must be unique andgenerate a unique sequence of values for the column: | new_data.student_id.value_counts().max() | _____no_output_____ | MIT | tutorials/single_table_data/04_TVAE_Model.ipynb | HDI-Project/SDV |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.