markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Trying the Koren's triode phenomenological model.
$$E_1 = \frac{E_{G2}}{k_P} log\left(1 + exp^{k_P (\frac{1}{u} + \frac{E_{G1}}{E_{G2}})}\right)$$
$$I_P = \left(\frac{{E_1}^X}{k_{G1}}\right) \left(1+sgn(E_1)\right)atan\left(\frac{E_P}{k_{VB}}\right)$$
Need to fit $X, k_{G1}, k_P, k_{VB}$ | mu = 11.0
def sgn(val):
if val >= 0:
return 1
if val < 0:
return -1
def funcKoren(x,X,kG1,kP,kVB):
rv = []
for VV in x:
EG2 = VV[0]
EG1 = VV[1]
EP = VV[2]
if kP < 0:
kP = 0
#print EG2,EG1,EP,kG1,kP,kVB,exp(kP*(1/mu + EG1/EG2))
... | experiments/02-modeling/pentode/pentode-modeling.ipynb | holla2040/valvestudio | mit |
<pre>
SPICE model
see http://www.normankoren.com/Audio/Tubemodspice_article_2.html#Appendix_A
.SUBCKT 6550 1 2 3 4 ; P G1 C G2 (PENTODE)
+ PARAMS: MU=7.9 EX=1.35 KG1=890 KG2=4200 KP=60 KVB=24
E1 7 0 VALUE={V(4,3)/KP*LOG(1+EXP((1/MU+V(2,3)/V(4,3))*KP))}
G1 1 3 VALUE={(PWR(V(7),EX)+PWRS(V(7),EX))/KG1*ATAN(V(1,3)/KVB)}... | EG2 = x[0][0]
def IaCalcKoren(EG1,EP):
global X,kG1,kP,kVB,mu
E1 = (EG2/kP) * log(1 + exp(kP*(1/mu + EG1/EG2)))
if E1 > 0:
IP = (pow(E1,X)/kG1)*(1 + sgn(E1))*atan(EP/kVB)
else:
IP = 0
return IP
Vgk = np.linspace(0,-32,9)
Vak = np.linspace(0,400,201)
vIaCalcKoren = np.vectorize(Ia... | experiments/02-modeling/pentode/pentode-modeling.ipynb | holla2040/valvestudio | mit |
Graf da osnovno idejo o tem, kaj uporabiti | ratingsNum=list()
for number in np.arange(1,10):
ratingsNum.append(len(data[data[:,2]==number,2]))
plt.figure()
plt.bar(np.arange(1,10),ratingsNum, 0.8, color="blue")
plt.show() | BaseClass/Porazdelitve.ipynb | sorter43/PR2017LSBOLP | apache-2.0 |
Ker imamo vnaprej dolečen interval, ki ne ustreza Gaussu najbolje, sem se odločil uporabiti beta porazdelitev | from scipy.stats import beta
a=8
b=2
n=1000
sample=beta.rvs(a, b, size=n)
xr = np.linspace(0, 1, 100)# interval X
P = [beta.pdf(x, a, b) for x in xr] # porazdelitvena funkcija
# Histogram - porazdelitev naključlnih VZORCEV x glede na P(x)
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.title("Vzorec")
plt... | BaseClass/Porazdelitve.ipynb | sorter43/PR2017LSBOLP | apache-2.0 |
这里本身我要输出(1,2,3 )但是在ipython中'_'自动识别成最新的(上一个值) 类似于matlab 中的ans
当然在python中这个多变量赋值字符串中也可以,任何迭代对象 | s = 'acfun'
a,b,c,d,e = s
a
e | data_structure_and_algorithm_py2_1.ipynb | zlxs23/Python-Cookbook | apache-2.0 |
只要将两边的变量或赋值数对齐就可利用任何迭代对象
1.2 解压可迭代对象赋值给多个变量
Python的星号表达式可以用来解决这个问题:如果一个可迭代对象的元素个数超过变量个数时,会抛出一个 ValueError 。 那么怎样才能从这个可迭代对象中解压出N个元素出来?
其实这里* 表示python中的可变参数 | record = ('maz',18,'13679259627','62627')
name,age,*tel = record
len(record)
name,age,*tel = record
name,age,**tel = record | data_structure_and_algorithm_py2_1.ipynb | zlxs23/Python-Cookbook | apache-2.0 |
不科学啊,怎么星号没有用了 | 2**4
*ta = record | data_structure_and_algorithm_py2_1.ipynb | zlxs23/Python-Cookbook | apache-2.0 |
2. Uso de Pandas para descargar datos de precios de cierre
Una vez cargados los paquetes, es necesario definir los tickers de las acciones que se usarán, la fuente de descarga (Yahoo en este caso, pero también se puede desde Google) y las fechas de interés. Con esto, la función DataReader del paquete pandas_datareader ... | assets = ['AAPL','MSFT','AA','AMZN','KO','QAI']
closes = portfolio_func.get_historical_closes(assets, '2016-01-01', '2017-09-22') | 02. Parte 2/15. Clase 15/.ipynb_checkpoints/11Class NB-checkpoint.ipynb | jdsanch1/SimRC | mit |
Par exemple si nous nous intéressons a l'évolution du cours des actions (valeurs) de différentes entreprises cette année, nous verrons que la pluspart des outils existent et sont disponibles.
Valeurs recherchées :
IBM
YELP
GOOGLE
BRUKER | symbols_list = ['IBM','YELP', 'GOOG']
for ticker in symbols_list:
d[ticker] = DataReader(ticker, "yahoo", '2016-01-01')
# L'execution de cette fonction précise que vous ayez accés à Internet
pan = pandas.Panel(d)
df1 = pan.minor_xs('Adj Close')
px=df1.asfreq('B',method='pad')
rets = px.pct_change()
((1+ rets).cum... | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
2) Visualisation géométrique | from mpl_toolkits.mplot3d import *
import matplotlib.pyplot as plt
import numpy as np
from random import random, seed
from matplotlib import cm
#%%%%%%%%% Presentation d'une bulle rouge %%%%%%%%#
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi,... | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
Visualisation d'un phénomène physique
L'equation de Biot-et-Savart | import numpy as np
# Constantes
my0=4*np.pi*1e-7; # perméabilité du vide
I0=-1; # Amplitude du courant
# le courant circule de gauche à droite
# Dimensions
d=25 # Diametre de la spire (mm)
segments=100 # discretization de la spire
alpha = 2*np.pi/(segments-1) # discretization de l... | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
$$B(x)=\frac{\mu_o}{4\pi}.I_o.\frac{r^2}{2 (r^2 +x^2)^{3/2} }$$ | #%%%%%%%%%%% Visualisation %%%%%%%%%%%%%%%%%%%%%%%#
plt.plot(np.linspace(xmin, xmax, ndp, endpoint = True) , bxf,'bo')
plt.plot(np.linspace(xmin, xmax, ndp, endpoint = True) , bx_analytique,'r-') | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
Une autre manière de définir les fonctions : les Lambdas | def my_funct(f,arg):
return f(arg)
my_funct(lambda x : 2*x*x,5) | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
Lambda est un racourci pour créer des fonctions anonymes
Elles ne sont pas plus faciles à ecrire | a=(lambda x: x*x)(8)
print(a)
def polynome(x):
return x**2 + 5*x + 4
racine=-4
print("La racine d'un polynome est la valeur pour laquelle est {0} " \
.format(polynome(racine)))
print("Avec un lambda c'est plus simple : ",end="")
print((lambda x:x**2 + 5*x + 4)(-4))
X=np.linspace(-10,10,50,endpoint = True)
... | Cours13-DILLMANN-ISEP2016.ipynb | DillmannFrench/Intro-PYTHON | gpl-3.0 |
Critical to note that this ignores the queuing and assumes that xx people are processed at each time interval at the counter. This will be used in conjunction with the scanner output to choose the bottle neck at each point in time | EXIT_NUMER = zip(FRISK_PATTERN,SCAN_PATTERN)
EXIT_NUMBER = [min(k) for k in EXIT_NUMER]
#plot(EXIT_NUMBER,'o')
#show()
EXIT_PATTERN = []
for index, item in enumerate(EXIT_NUMBER):
EXIT_PATTERN += [index]*item
| Blog Post Content/Airport Waiting Time.ipynb | akshayrangasai/akshayrangasai.github.io | mit |
Minimum number of processed people between the scanners and the frisking is the bottleneck at any given time, and this will be the exit rate at any given time. | RESIDUAL_ARRIVAL_PATTERN = ARRIVAL_LIST[0:len(EXIT_PATTERN)]
WAIT_TIMES = [m-n for m,n in zip(EXIT_PATTERN,RESIDUAL_ARRIVAL_PATTERN)]
#print EXIT_PATTERN
'''
for i,val in EXIT_PATTERN:
WAIT_TIMES += [ARRIVAL_PATTERN(i) - val]
'''
plot(WAIT_TIMES,'r-')
ylabel('Wait times for people entering the queue')
xlabel... | Blog Post Content/Airport Waiting Time.ipynb | akshayrangasai/akshayrangasai.github.io | mit |
Building predictive models
First we will split our data into features and the target: | data.head()
X_train = data.drop(columns='species')
y_train = data['species'].values | rampwf/tests/kits/iris/iris_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
A basic predictive model using the scikit-learn random forest classifier will be presented below: | from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier(n_estimators=1, max_leaf_nodes=2, random_state=61) | rampwf/tests/kits/iris/iris_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
We can cross-validate our classifier (clf) using cross_val_score. Below we will have specified cv=8 meaning KFold cross-valdiation splitting will be used, with 8 folds. The accuracy classification score is calculated for each split. The output score will be an array of 8 scores from each KFold. The score mean and stand... | from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, X_train, y_train, cv=8, scoring='accuracy')
print("mean: %e (+/- %e)" % (scores.mean(), scores.std())) | rampwf/tests/kits/iris/iris_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
RAMP submissions
For submitting to the RAMP site, you will need to write a submission.py file that defines a get_estimator function that returns a scikit-learn estimator.
For example, to submit our basic example above, we would define our classifier clf within the function and return clf at the end. Remember to include... | from sklearn.ensemble import RandomForestClassifier
def get_estimator():
clf = RandomForestClassifier(n_estimators=1, max_leaf_nodes=2,
random_state=61)
return clf | rampwf/tests/kits/iris/iris_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
If you take a look at the sample submission in the directory submissions/starting_kit, you will find a file named classifier.py, which has the above code in it.
You can test that the sample submission works by running ramp_test_submission in your terminal (ensure that ramp-workflow has been installed and you are in the... | !ramp_test_submission | rampwf/tests/kits/iris/iris_starting_kit.ipynb | paris-saclay-cds/ramp-workflow | bsd-3-clause |
Path to configuration file with login information to the AAS SQL server | config_filename = "/Users/adrian/projects/aas-abstract-sorter/sql_login.yml"
with open(config_filename) as f:
config = yaml.load(f.read()) | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Establish a database connection | engine = create_engine('mysql+pymysql://{user}:{password}@{server}/{database}'.format(**config))
engine.connect()
_presentation_cache = dict() | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Get all presentations and sessions from AAS 227 | query = """
SELECT session.so_id, presentation.title,
presentation.abstract, presentation.id
FROM session, presentation
WHERE session.meeting_code = 'aas227'
AND session.so_id = presentation.session_so_id
AND presentation.status IN ('Sessioned', '')
AND session.type IN (
'Oral Session'
, 'Special Ses... | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Define a scikit-learn count vectorizer with a custom word tokenizer | # based on http://www.cs.duke.edu/courses/spring14/compsci290/assignments/lab02.html
stemmer = PorterStemmer()
def stem_tokens(tokens, stemmer):
stemmed = []
for item in tokens:
stemmed.append(stemmer.stem(item))
return stemmed
def tokenize(text):
# remove non letters
text = re.sub("[^a-zA-... | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Fit the count vectorizer to all AAS abstracts from AAS 227 | count_matrix = vectorizer.fit_transform(presentation_df['abstract']).toarray()
count_matrix.shape | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
As a quick check, what are the 10 most common words in AAS abstracts? | ten_most_common_idx = count_matrix.sum(axis=0).argsort()[::-1][:10]
feature_words = np.array(vectorizer.get_feature_names())
print(feature_words[ten_most_common_idx]) | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
For each pair of abstracts, compute the cosine similarity | similiarity_matrix = np.zeros((count_matrix.shape[0],count_matrix.shape[0]))
for ix1 in range(count_matrix.shape[0]):
for ix2 in range(count_matrix.shape[0]):
num = count_matrix[ix1].dot(count_matrix[ix2])
denom = np.linalg.norm(count_matrix[ix1]) * np.linalg.norm(count_matrix[ix2])
... | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Find the top ten most similar abstracts | similiarity_matrix_1d = np.triu(similiarity_matrix).ravel()
top_ten = sorted(np.unique(similiarity_matrix_1d[~np.isclose(similiarity_matrix_1d,1.)]), reverse=True)[:10]
for ix1,ix2 in zip(list(ix[0]), list(ix[1])):
pres1 = get_presentation(presentation_ids[ix1])
pres2 = get_presentation(presentation_ids[ix2])
... | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Those seem pretty similar! Looks like the code is working...
Now we'll predict which simultaneous sessions have the most overlap
For now, we'll start with the first day of conference talks, 5 Jan. We'll also only check for sessions that have the same start time (of course, we should really be looking at any overlapping... | def session_similarity(so_id1, so_id2):
"""
Compute the similarity between two sessions by getting the sub-matrix of the
similarity matrix for all pairs of presentations from each session.
"""
presentations_session1 = presentation_df[presentation_df['so_id'] == so_id1]
presentations_session2 = ... | notebooks/AAS abstract similarity.ipynb | adrn/AASAbstractSorter | mit |
Toy data from HTF, p. 339 | def htf_p339(n_samples=2000, p=10, random_state=None):
random_state=check_random_state(random_state)
## Inputs
X = random_state.normal(size=(n_samples, max(10, p)))
## Response: \chi^2_10 0.5-prob outliers
y = (np.sum(X[:, :10]**2, axis=1) > 9.34).astype(int).reshape(-1)
return X, y | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Fix the RNG | random_state = np.random.RandomState(0xC01DC0DE) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Generate four samples | X_train, y_train = htf_p339(2000, 10, random_state)
X_test, y_test = htf_p339(10000, 10, random_state)
X_valid_1, y_valid_1 = htf_p339(2000, 10, random_state)
X_valid_2, y_valid_2 = htf_p339(2000, 10, random_state) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Ensemble methods
In general any ensemble methods can be broken down into the following two
stages, possibly overlapping:
1. Populate a dictionary of base learners;
2. Combine them to get a composite predictor.
Many ML estimators can be considerd ensemble methods:
1. Regression is a linear ensemble of basis funct... | from sklearn.tree import DecisionTreeClassifier
clf1_ = DecisionTreeClassifier(max_depth=1,
random_state=random_state).fit(X_train, y_train)
clf2_ = DecisionTreeClassifier(max_depth=3,
random_state=random_state).fit(X_train, y_train)
clf3_ = DecisionTreeCla... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Bagging
Bagging is meta algortihm that aims at constructing an esimator by averaging
many noisyб but approximately unbiased models. The general idea is that averaging
a set of unbiased estimates, yields an estimate with much reduced variance
(provided the base estimates are uncorrelated).
Bagging works poorly on model... | from sklearn.ensemble import BaggingClassifier, BaggingRegressor | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Both Bagging Calssifier and Regressor have similar parameters:
- n_estimators -- the number of estimators in the ensemble;
- base_estimator -- the base estimator from which the bagged ensemble is
built;
- max_samples -- the fraction of samples to be used to train each
individual base estimator. Choosing max_samples <... | clf1_ = BaggingClassifier(n_estimators=10,
base_estimator=DecisionTreeClassifier(max_depth=3),
random_state=random_state).fit(X_train, y_train)
clf2_ = BaggingClassifier(n_estimators=10,
base_estimator=DecisionTreeClassifier(max_depth=None),
... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Random Forest
Essentially, a random forest is an bagging ensemble constructed from a large collection
of decorrelated regression/decision trees. The algorithm specifially modifies
the tree induction procedure to produce trees with as low correlation as possible.
1. for $b=1,\ldots, B$ do:
1. Draw a bootstra... | from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
As with Bagging, Random Forest Classifier and Regressor accept similar parametrs:
- criterion -- the function to measure the quality of a split. Supported criteria
are:
* "gini" -- Gini impurity (classification only);
* "entropy" -- the information gain (classification only);
* "mse" -- mean squared error (... | clf1_ = RandomForestClassifier(n_estimators=10, max_depth=3,
random_state=random_state).fit(X_train, y_train)
clf2_ = RandomForestClassifier(n_estimators=100, max_depth=3,
random_state=random_state).fit(X_train, y_train)
clf3_ = RandomForestClassifier(n_esti... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Boosting
Classification
The underlying idea of boosting is to combine a collection of weak predictors,
into one strong powerful committee model. Most commonly a dictionary of nonlinear
base predictors, like decision trees (regression/classification), is used weak
predictors in boosting.
Consider the following cl... | from sklearn.ensemble import AdaBoostClassifier, AdaBoostRegressor | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Common parameters:
- n_estimators -- the maximum number of estimators at which boosting is
terminated (in case of perfect fit, the learning procedure is stopped early);
- base_estimator -- the base estimator, which supports sample weighting,
from which the boosted ensemble is built;
- learning_rate -- learning rate shr... | clf1_ = AdaBoostClassifier(n_estimators=10,
base_estimator=DecisionTreeClassifier(max_depth=1),
random_state=random_state).fit(X_train, y_train)
clf2_ = AdaBoostClassifier(n_estimators=100,
base_estimator=DecisionTreeClassifier(max_depth... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Gradient boosting
In certain circumstances in order to minimize a convex twice-differentiable
function $f:\mathbb{R}^p \mapsto \mathbb{R}$ one uses Newton-Raphson iterative
procedure, which repeats until convergence this update step:
$$ x_{m+1} \leftarrow x_m - \bigl(\nabla^2 f(x_m)\bigr)^{-1} \nabla f(x_m) \,, ... | from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Both Gradient boosting ensembles in scikit accept the following paramters:
- loss -- loss function to be optimized:
* Classification:
* 'deviance' -- refers logistic regression with probabilistic outputs;
* 'exponential' -- gradient boosting recovers the AdaBoost algorithm;
* Regression:
... | clf1_ = GradientBoostingClassifier(n_estimators=10,
max_depth=1, learning_rate=0.75,
random_state=random_state).fit(X_train, y_train)
clf2_ = GradientBoostingClassifier(n_estimators=100,
max_depth=1, learning_rate=0... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Large ensemble, small learning rate | clf1_ = GradientBoostingClassifier(n_estimators=100,
max_depth=1, learning_rate=0.1,
random_state=random_state).fit(X_train, y_train)
clf2_ = GradientBoostingClassifier(n_estimators=1000,
max_depth=1, learning_rate=... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
XGBoost
Briefly, XGBoost, is a higlhy streamlined open-source gradient boosting library, which
supports many useful loss functions and uses second order loss approximation both
to increas the ensemble accuracy and speed of convergence:
1. learning rate $\eta>0$ to regulate the convergence;
2. offer $l_1$ and $l_... | import xgboost as xg
seed = random_state.randint(0x7FFFFFFF) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Scikit-Learn interface | clf_ = xg.XGBClassifier(
## Boosting:
n_estimators=50,
learning_rate=0.1,
objective="binary:logistic",
base_score=0.5,
## Regularization: tree growth
max_depth=3,
gamma=0.5,
min_child_weight=1.0,
max_delta_step=0.0,
subsample=1.0,
colsample_bytree=1.0,
colsample_bylevel=1.0,
... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Internally XGBoost relies heavily on a custom dataset format DMatrix.
The interface, which is exposed into python has three capabilities:
- load datasets in libSVM compatible format;
- load SciPy's sparse matrices;
- load Numpy's ndarrays.
The DMatrix class is constructed with the following parameters:
- data : Data so... | dtrain = xg.DMatrix(X_train, label=y_train, missing=np.nan)
dtest = xg.DMatrix(X_test, missing=np.nan)
dvalid1 = xg.DMatrix(X_valid_1, label=y_valid_1, missing=np.nan)
dvalid2 = xg.DMatrix(X_valid_2, label=y_valid_2, missing=np.nan) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
The same XGBoost classifier as in the Scikit-learn example. | param = dict(
## Boosting:
eta=0.1,
objective="binary:logistic",
base_score=0.5,
## Regularization: tree growth
max_depth=3,
gamma=0.5,
min_child_weight=1.0,
max_delta_step=0.0,
subsample=1.0,
colsample_bytree=1.0,
colsample_bylevel=1.0,
## Regularization: leaf weights
reg_al... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Both the sklearn-compatible and basic python interfaces have the similar
parameters. Except they are passed slightly differently.
Gradient boosting parameters:
- eta, learning_rate ($\eta$) -- step size shirinkage factor;
- n_estimators, num_boost_round ($M$) -- the size of the ensemble, number of boosting rounds;
- ob... | clf1_ = xg.XGBClassifier(n_estimators=10,
max_depth=1, learning_rate=0.1,
seed=seed).fit(X_train, y_train)
clf2_ = xg.XGBClassifier(n_estimators=1000,
max_depth=1, learning_rate=0.1,
seed=seed).fit(X_train, y_train)
cl... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Other methods
Stacking
Every ensemble method comprises of essentially two phases:
1. population of a dictionary of base learners (models, like classification
trees in AdaBoost, or regression trees in GBRT);
2. aggregation of the dictionary into a sinlge estimator;
These phases are not necessarily separated: in B... | from sklearn.base import clone
from sklearn.cross_validation import KFold
def kfold_stack(estimators, X, y=None, predict_method="predict",
n_folds=3, shuffle=False, random_state=None,
return_map=False):
"""Splits the dataset into `n_folds` (K) consecutive folds (without shuffling
... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Examples
Combining base classifiers using Logistic Regression is a typical example of how
first level features $x\in \mathcal{X}$ are transformed by $\hat{f}m:\mathcal{X}\mapsto \mathbb{R}$
into second-level meta features $(\hat{f}_m(x)){m=1}^M \in \mathbb{R}^M$, that
are finally fed into a logistic regression, that do... | seed = random_state.randint(0x7FFFFFFF) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Define the first-level predictors. | from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
estimators_ = [
RandomForestClassifier(n_estimators=200, max_features=0.5, n_jobs=-1, random_state=seed),
GradientBoostingClassifier(n_estimators=200, max_depth=3, learning_rate=0.75, random_state=seed),
BaggingClassifier(n_e... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Create meta features for the train set: using $K$-fold stacking estimate the class-1
probabilities $\hat{p}i = (\hat{p}{mi}){m=1}^M = (\hat{f}^{-k_i}_m(x_i)){m=1}^M$
for every $i=1,\ldots, n$. | meta_train_ = kfold_stack(estimators_, X_train, y_train,
n_folds=5, predict_method="predict_proba")[..., 1] | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Now using the whole train, create test set meta features: $p_j = (\hat{f}m(x_j)){m=1}^M$
for $j=1,\ldots, n_{\text{test}}$. Each $\hat{f}_m$ is estimated on the whole train set. | fitted_ = [clone(est_).fit(X_train, y_train) for est_ in estimators_]
meta_test_ = np.stack([fit_.predict_proba(X_test) for fit_ in fitted_], axis=1)[..., 1] | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
The prediction error of each individual classifier (trained on the whole train dataset). | base_scores_ = pd.Series([1 - fit_.score(X_test, y_test) for fit_ in fitted_],
index=estimator_names_)
base_scores_ | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Now using $10$-fold cross validation on the train dataset $(\hat{p}i, y_i){i=1}^n$,
find the best $L_1$ regularization coefficient $C$. | from sklearn.grid_search import GridSearchCV
grid_cv_ = GridSearchCV(LogisticRegression(penalty="l1"),
param_grid=dict(C=np.logspace(-3, 3, num=7)),
n_jobs=-1, cv=5).fit(meta_train_, y_train)
log_ = grid_cv_.best_estimator_
grid_cv_.grid_scores_ | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
The weights chosen by logisitc regression are: | from math import exp
print "Intercept:", log_.intercept_, "\nBase probability:", 1.0/(1+exp(-log_.intercept_))
pd.Series(log_.coef_[0], index=estimator_names_) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Let's see how well the final model works on the test set: | print "Logistic Regression (l1) error:", 1 - log_.score(meta_test_, y_test) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
and the best model | log_ | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Voting Classifier
This is a very basic method of constructing an aggregated classifier from a finite dictionary.
Let $\mathcal{V}$ be the set of classifiers (voters), with each calssifier's class probablilites
given by $\hat{f}_v:\mathcal{X}\mapsto\mathbb{[0,1]}^K$ and prediction
$\hat{g}_v(x) = \mathtt{MAJ}(\ha... | from sklearn.ensemble import VotingClassifier | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
VotingClassifier options:
- estimators -- The list of classifiers;
- voting -- Vote aggregation strategy:
* "hard" -- use predicted class labels for majority voting;
* "soft" -- use sums of the predicted probalities for determine
the most likely class;
- weights -- weight the occurrences of predicted class ... | clf1_ = VotingClassifier(list(zip(estimator_names_, estimators_)),
voting="hard", weights=None).fit(X_train, y_train)
clf2_ = VotingClassifier(list(zip(estimator_names_, estimators_)),
voting="soft", weights=None).fit(X_train, y_train)
print "Hard voting classifier er... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Let's use LASSO Least Angle Regression (LARS, HTF p. 73) to select weights of the
base calssifiers. | from sklearn.linear_model import Lars
lars_ = Lars(fit_intercept=False, positive=True).fit(meta_train_, y_train)
weights_ = lars_.coef_
pd.Series(weights_, index=estimator_names_) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Show the RMSE of lars, and the error rates of the base classifiers. | print "LARS prediction R2: %.5g"%(lars_.score(meta_test_, y_test),)
base_scores_ | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Let's see if there is improvement. | clf1_ = VotingClassifier(list(zip(estimator_names_, estimators_)),
voting="soft", weights=weights_.tolist()).fit(X_train, y_train)
print "Soft voting ensemble with LARS weights:", 1 - clf1_.score(X_test, y_test) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Indeed, this illustrates that clever selection of classifier weights might be profitable.
Another example on Voting Clasifier (from Scikit guide) | from sklearn.datasets import make_gaussian_quantiles
def scikit_example(n_samples, random_state=None):
X1, y1 = make_gaussian_quantiles(cov=2., n_samples=int(0.4*n_samples),
n_features=2, n_classes=2,
random_state=random_state)
X2, y2 = m... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Get a train set, a test set, and a $2$-d mesh for plotting. | from sklearn.cross_validation import train_test_split
X2, y2 = scikit_example(n_samples=1500, random_state=random_state)
X2_train, X2_test, y2_train, y2_test = \
train_test_split(X2, y2, test_size=1000, random_state=random_state)
min_, max_ = np.min(X2, axis=0) - 1, np.max(X2, axis=0) + 1
xx, yy = np.meshgrid(np.l... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Make a dictionary of simple classifers | from sklearn.neighbors import KNeighborsClassifier
classifiers_ = [
("AdaBoost (100) DTree (3 levels)",
AdaBoostClassifier(n_estimators=100, base_estimator=DecisionTreeClassifier(max_depth=3),
random_state=random_state)),
("KNN (k=3)", KNeighborsClassifier(n_neighbors=3)),
("... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Show the decision boundary. | from itertools import product
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
for i, (name_, clf_) in zip(product([0, 1], [0, 1]), estimators_):
clf_.fit(X2_train, y2_train)
prob_ = clf_.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1].reshape(xx.shape)
axes[i[0], i[1]].contourf(xx, yy, prob_, alpha=0.4... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Let's see if this simple soft-voting ensemble improved the test error. | for name_, clf_ in estimators_:
print name_, " error:", 1-clf_.score(X2_test, y2_test) | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
<hr/>
Example from HTF pp. 339 - 340
Now let's inspect the test error as a function of the size of the ensemble | stump_ = DecisionTreeClassifier(max_depth=1).fit(X_train, y_train)
t224_ = DecisionTreeClassifier(max_depth=None, max_leaf_nodes=224).fit(X_train, y_train)
ada_ = AdaBoostClassifier(n_estimators=400, random_state=random_state).fit(X_train, y_train)
bag_ = BaggingClassifier(n_estimators=400, random_state=random_state,
... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Get the prediction as a function of the memebers in the ensemble. | def get_staged_accuracy(ensemble, X, y):
prob_ = np.stack([est_.predict_proba(X)
for est_ in ensemble.estimators_],
axis=1).astype(float)
pred_ = np.cumsum(prob_[..., 1] > 0.5, axis=1).astype(float)
pred_ /= 1 + np.arange(ensemble.n_estimators).reshape((1, -1))
... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
Plot the test error. | fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111)
ax.set_ylim(0, 0.50) ; ax.set_xlim(-10, ada_.n_estimators)
ax.plot(1+np.arange(ada_.n_estimators), 1-ada_scores_, c="k", label="AdaBoost")
ax.plot(1+np.arange(bag_.n_estimators), 1-bag_scores_, c="m", label="Bagged DT")
ax.plot(1+np.arange(bag_.n_estimators), 1... | year_15_16/machine_learning_course/ensemble_practicum/ensemble_methods_scikit.ipynb | ivannz/study_notes | mit |
u > 0 | def f1_numpy(r, u, c):
return (r*c**2)/2 + (u*c**4)/4
n = 2
T = np.linspace(-n,n,101) | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
f vs c
r(T) > 0 | fig1 = plt.figure(figsize=(11,8))
ax1 = fig1.gca()
plt.plot(T, f1_numpy(1, 1, T))
plt.xlabel('c', fontsize=14)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=14)
ax1.yaxis.set_label_coords(0.53,1)
ax1.xaxis.set_label_coords(1.03,0.22)
ax1.spines['left'].set_position('zero')
ax1.spines['righ... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
r(T) < 0 | fig2 = plt.figure(figsize=(11,8))
ax2 = fig2.gca()
# ax2.get_yticklabels()[0].set_visible(False)
plt.plot(T, f1_numpy(-1, 1, T))
plt.xlabel('c', fontsize=16)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=16)
ax2.yaxis.set_label_coords(0.53,1)
ax2.xaxis.set_label_coords(1.03,0.22)
ax2.spine... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
c vs T (or r(T))
Solution for $c_{min}$:
$c_{min} = \pm\sqrt{\dfrac{-r(T)}{u}}$ | def c1(r,u):
a = []
for i in r:
if i < 0:
a.append(np.sqrt(-i/u))
else:
a.append(0)
return np.array(a)
x = np.linspace(0,2,100)
plt.figure(figsize=(11,8))
plt.plot(x, c1(x-0.5,1),label='+')
plt.plot(x, -c1(x-0.5,1),label='-')
plt.xlabel('T',fontsize=16)
plt.ylabel('... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
u < 0 | def f2_numpy(r, u, v, c):
return (r*c**2)/2 - (abs(u)*c**4)/4 + (abs(v)*c**6)/6 | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Large r | fig3 = plt.figure(figsize=(11,8))
ax3 = fig3.gca()
plt.plot(T, f2_numpy(1, -1, 1, T))
plt.xlabel('c', fontsize=14)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=14)
ax3.yaxis.set_label_coords(0.53,1)
ax3.xaxis.set_label_coords(1.03,0.22)
ax3.spines['left'].set_position('zero')
ax3.spines['... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Small r | fig4 = plt.figure(figsize=(11,8))
ax4 = fig4.gca()
plt.plot(T, f2_numpy(0.23, -1, 1, T))
plt.xlabel('c', fontsize=14)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=14)
ax4.yaxis.set_label_coords(0.53,1)
ax4.xaxis.set_label_coords(1.03,0.22)
ax4.spines['left'].set_position('zero')
ax4.spine... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Smaller r | fig5 = plt.figure(figsize=(11,8))
ax5 = fig5.gca()
plt.plot(T, f2_numpy(0.187302, -1, 1, T))
plt.xlabel('c', fontsize=14)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=14)
ax5.yaxis.set_label_coords(0.53,1)
ax5.xaxis.set_label_coords(1.03,0.22)
ax5.spines['left'].set_position('zero')
ax5.s... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Even smaller r | fig6 = plt.figure(figsize=(11,8))
ax6 = fig6.gca()
plt.plot(T, f2_numpy(0.15, -1, 1, T))
plt.xlabel('c', fontsize=14)
plt.ylabel('f', rotation='horizontal',verticalalignment='center', fontsize=14)
ax6.yaxis.set_label_coords(0.53,1)
ax6.xaxis.set_label_coords(1.03,0.22)
ax6.spines['left'].set_position('zero')
ax6.spine... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
c vs r(T) (general)
The solutions for $c_{min}$:
$c_{min} = \pm\sqrt{\dfrac{|u| \pm \sqrt{|u|^{2} - 4r(T)|v|}}{2|v|}}$
Conditions for the following cell:
$c_{min,+} = \pm\sqrt{\dfrac{|u| + \sqrt{|u|^{2} - 4r(T)|v|}}{2|v|}}$ for $\sqrt{|u| + \sqrt{|u|^{2} - 4r(T)|v|}}, \sqrt{|u|^{2} - 4r(T)|v|} > 0$
$c_{min,-} = \pm\sqr... | #might not be the best code to use
def c2(r, u, v):
a = []
for i in r:
if (abs(u)-np.sqrt(abs(u)**2-4*i*abs(v)) > 0) and (np.sqrt(abs(u)**2-4*i*abs(v)) > 0):
a.append(np.sqrt((abs(u)-np.sqrt(abs(u)**2-4*i*abs(v)))/(2*abs(v))))
elif (abs(u)+np.sqrt(abs(u)**2-4*i*abs(v)) > 0) and (np.s... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
c vs r(T) (specific)
$r_{1} = \dfrac{|u|^{2}}{4|v|}$ for $c_{+} = \sqrt{\dfrac{|u| + \sqrt{|u|^{2} - 4r|v|}}{2|v|}}$
$r_{2} = 0$ for $c_{-} = \sqrt{\dfrac{|u| - \sqrt{|u|^{2} - 4r|v|}}{2|v|}}$
after solving for $\dfrac{dc}{dr} = \infty$ for both cases. | plt.figure(figsize=(11,8))
plt.plot(s,np.sqrt((abs(-1)+np.sqrt(abs(-1)**2-4*s*abs(1)))/(2*abs(1))),c='b',label='$\mathregular{c_{min,+}}$')
plt.plot(s,np.sqrt((abs(-1)-np.sqrt(abs(-1)**2-4*s*abs(1)))/(2*abs(1))),c='g',label='$\mathregular{c_{min,-}}$')
# plt.plot(s,-np.sqrt((abs(-1)+np.sqrt(abs(-1)**2-4*s*abs(1)))/(2*a... | Smectic/SmAtoSmC.ipynb | brettavedisian/Liquid-Crystals-Summer-2015 | mit |
Here are some examples of basic symbol operations: | x = sympy.Symbol('x')
y = x
x, x*2+1, y, type(y), x == y
try:
x*y+z
except NameError as e:
print(e)
sympy.symbols('x5:10'), sympy.symbols('x:z')
X = sympy.numbered_symbols('variable')
[ next(X) for i in range(5) ] | files/Process.ipynb | jimaples/jimaples.github.io | mit |
SymPy also handles expressions: | e = sympy.sympify('x*(x-1)+(x-1)')
e, sympy.factor(e), sympy.expand(e) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
But most work of interest is more than single expressions, so here is a helper function to handle systems of equations. | from process import parseExpr
help(parseExpr)
import inspect
print(inspect.getsource(parseExpr)) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Example Use Case
Let's use a simple example to explore the additional functionality. Performing a 2-D rotation involves multiple dependant variables, independant variables, and functions.
$x' = x \cos \theta - y \sin \theta$
$y' = x \sin \theta + y \cos \theta$ | inputs='x y theta'
outputs="x' y'"
expr='''
x' = x*cos(theta) - y*sin(theta)
y' = x*sin(theta) + y*cos(theta)
'''
ins = sympy.symbols(inputs)
outs = sympy.symbols(outputs)
eqn = dict(parseExpr(expr))
# No quote marks, the dictionary keys are SymPy symbols
ins, outs, eqn | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Expression Trees
SymPy maintains a tree for all expressions. Everything in SymPy has .args and .func arguments that allow the expression (at that point in the tree) to be reconstructed. The .func argument is essentially the same as calling type and specifies whether the node is a add, multiply, cosine, some other funct... | expr_inputs = set()
expr_functs = set()
for arg in sympy.preorder_traversal(eqn[outs[0]]):
print(arg.func, '\t', arg, '\t', arg.args)
if arg.is_Symbol:
expr_inputs.add(arg)
elif arg.is_Function:
expr_functs.add(arg.func)
expr_inputs, expr_functs | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Adding Functionality
Before we go on, let's create a class around parseExpr so we can add object-oriented functionality. | from process import Block
print(inspect.getdoc(Block))
b = Block(expr, '2-D Rotate', inputs, outputs)
# spoiler alert!
print(inspect.getsource(Block.__init__)) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Convert SymPy equations to text
Links: Top
Intro
Text
LaTeX
Solver
Evaluating
Designs
Help | print('\n'.join( str(k)+' = '+sympy.pretty(v) for k,v in eqn.items() ))
print()
print('\n'.join( str(k)+' = '+str(v) for k,v in eqn.items() )) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
So our Block instance can do the same thing, it needs to have pretty and __str__ functions defined. A __repr__ function could also be used to return a separate representation of the object. | b.pretty()
print(b)
print(inspect.getsource(b.pretty))
print(inspect.getsource(b.__str__)) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Convert SymPy equations to LaTeX
Strings are well and good, but don't quite cut it for publications and presentations
Links: Top
Intro
Text
LaTeX
Solver
Evaluating
Designs
Help | # Generate a LaTeX string for the Jupyter notebook to render
print(' \\\\\n'.join([ str(k)+' = '+sympy.latex(v) for k, v in eqn.items() ]))
%%latex
$
x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}
$ | files/Process.ipynb | jimaples/jimaples.github.io | mit |
For our Block instance, the latex function doesn't need any arguments, so it can be handled as an attribute | print(b.latex)
%%latex
$
\underline{\verb;Block: 2-D Rotate;} \\
x' = x \cos{\left (\theta \right )} - y \sin{\left (\theta \right )} \\
y' = x \sin{\left (\theta \right )} + y \cos{\left (\theta \right )}
$
f = inspect.getsource(Block).split('def ')
for i,s in enumerate(f):
if s.startswith('latex'):
# ... | files/Process.ipynb | jimaples/jimaples.github.io | mit |
As a property, the latex function above is implicitly called instead of returning the function itself. Attempting to use inspect.getsource results in a TypeError since the LaTeX output isn't source code. | try:
inspect.getsource(getattr(Block,'latex'))
except TypeError as e:
print(type(e),' : ', e) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
We've seen a couple SymPy output formats. The init_printing function provides a lot of additional control over how symbols and expressions are shown, including LaTeX. | b.eqn
sympy.init_printing(use_latex=True)
#sympy.init_printing(use_latex=False)
b.eqn
sympy.Matrix(b.eqn)
help(sympy.init_printing) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Rearranging Equations
SymPy can also handle sets of equations (sympy.Eq instances) to handle intermediate values or solve equations in terms of desired variables. Block can catch up later.
Links: Top
Intro
Text
LaTeX
Solver
Evaluating
Designs
Help | inputs='x y theta'
outputs="x' y'"
expr='''
x' = x*c - y*s
y' = x*s + y*c
c = cos(theta)
s = sin(theta)
'''
ins2 = sympy.symbols(inputs)
outs2 = sympy.symbols(outputs)
hidden2 = sympy.symbols('c s')
eqn2 = tuple(sympy.Eq(k,v) for k, v in parseExpr(expr))
ins2, outs2, eqn2
sympy.solve(eqn2, outs2+hidden2)
help(sympy.... | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Evaluating Expressions
SymPy can evaluate equations symbolically (.subs function) or numerically (.evalf function), at specified level of precision.
Links: Top
Intro
Text
LaTeX
Solver
Evaluating
Designs
Help | x = sympy.Symbol("x'")
eqn[x].subs(zip(ins, (1, 1, 45)))
eqn[x].evalf(4, subs=dict(zip(ins, (1, 1, 45))))
# sanity check with NumPy
import numpy as np
-1*np.sin(45) + np.cos(45)
e = sympy.sympify('sqrt(x)')
print(e.evalf(subs={'x':2}))
print(e.evalf(60, subs={'x':2}))
print(sympy.pi.evalf())
print(sympy.pi.evalf(10... | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Compiling Expressions
For efficiency, sympy.lambdify is preferred for numerical analysis. It supports mathematical functions from math, sympy.Function, or mpmath. Since these library functions are compiled Python, C, or even Fortran, they are significantly faster than sympy.evalf. | rad=np.linspace(0, np.pi, 8+1)
f = sympy.lambdify(ins, eqn[x], 'numpy')
%timeit f(1,0,rad)
%%timeit
for i in rad: # evalf doesn't support arrays!
eqn[x].evalf(subs={'x':1.0,'y':0.0,'theta':i}) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
SymPy also supports uFuncify for generating binary functions (using f2py and Cython) and Theano for GPU support. These options are discussed in the SymPy documentation. | help(sympy.lambdify) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Note that sympy.lambdify also supports custom functions (e.g. conditional operations or reshaping arrays). These custom functions can also be optimized for computing as easily as including a @jit decorator from the numba library. | def my_sample(x):
r = len(x) >> 1
return np.reshape(x[:2*r], (r,2))
x = np.linspace(0, np.pi, 9+1)
print(x*180/np.pi) # degrees
e = sympy.sympify('1+sample(x)')
print(e)
f = sympy.lambdify(sympy.Symbol('x'), e, {'sample':my_sample})
f(x)
f = sympy.lambdify(sympy.Symbol('x'), # inputs
... | files/Process.ipynb | jimaples/jimaples.github.io | mit |
However, the documentation could be better. (Earlier versions didn't even include the expresion.) | help(f) | files/Process.ipynb | jimaples/jimaples.github.io | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.