markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The default score method for the MKSHomogenizationModel is the R-squared value. Let's look at the how the mean R-squared values and their
standard deviations change as we varied the number of n_components and degree using
draw_gridscores_matrix from pymks.tools. | from pymks.tools import draw_gridscores_matrix
draw_gridscores_matrix(gs, ['n_components', 'degree'], score_label='R-Squared',
param_labels=['Number of Components', 'Order of Polynomial'])
| notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
For the parameter range that we searched, we have found that a model with 3rd order polynomial
and 3 components had the best R-squared value. It's difficult to see the differences in the score
values and the standard deviation when we have 3 or more components. Let's take a closer look at those values using draw_grid_... | from pymks.tools import draw_gridscores
gs_deg_1 = [x for x in gs.grid_scores_ \
if x.parameters['degree'] == 1][2:-1]
gs_deg_2 = [x for x in gs.grid_scores_ \
if x.parameters['degree'] == 2][2:-1]
gs_deg_3 = [x for x in gs.grid_scores_ \
if x.parameters['degree'] == 3][2:-1]
draw_... | notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
Prediction using MKSHomogenizationModel
Now that we have selected values for n_components and degree, lets fit the model with the data. Again because
our microstructures are periodic, we need to use the periodic_axes argument. | model.fit(X, y, periodic_axes=[0, 1])
| notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
Lastly, we can also evaluate our prediction by looking at a goodness-of-fit plot. We
can do this by importing draw_goodness_of_fit from pymks.tools. | from pymks.tools import draw_goodness_of_fit
fit_data = np.array([y, model.predict(X, periodic_axes=[0, 1])])
pred_data = np.array([y_new, y_predict])
draw_goodness_of_fit(fit_data, pred_data, ['Training Data', 'Testing Data'])
| notebooks/stress_homogenization_2D.ipynb | XinyiGong/pymks | mit |
Step 1: The Data Science of Shoelaces
Nike has hired you as a data science consultant to help them save money on shoe materials. Your first assignment is to review a model one of their employees built to predict how many shoelaces they'll need each month. The features going into the machine learning model include:
- Th... | # Check your answer (Run this code cell to receive credit!)
q_1.check() | notebooks/ml_intermediate/raw/ex7.ipynb | Kaggle/learntools | apache-2.0 |
Step 2: Return of the Shoelaces
You have a new idea. You could use the amount of leather Nike ordered (rather than the amount they actually used) leading up to a given month as a predictor in your shoelace model.
Does this change your answer about whether there is a leakage problem? If you answer "it depends," what doe... | # Check your answer (Run this code cell to receive credit!)
q_2.check() | notebooks/ml_intermediate/raw/ex7.ipynb | Kaggle/learntools | apache-2.0 |
Step 3: Getting Rich With Cryptocurrencies?
You saved Nike so much money that they gave you a bonus. Congratulations.
Your friend, who is also a data scientist, says he has built a model that will let you turn your bonus into millions of dollars. Specifically, his model predicts the price of a new cryptocurrency (like ... | # Check your answer (Run this code cell to receive credit!)
q_3.check() | notebooks/ml_intermediate/raw/ex7.ipynb | Kaggle/learntools | apache-2.0 |
Step 4: Preventing Infections
An agency that provides healthcare wants to predict which patients from a rare surgery are at risk of infection, so it can alert the nurses to be especially careful when following up with those patients.
You want to build a model. Each row in the modeling dataset will be a single patient w... | # Check your answer (Run this code cell to receive credit!)
q_4.check() | notebooks/ml_intermediate/raw/ex7.ipynb | Kaggle/learntools | apache-2.0 |
Step 5: Housing Prices
You will build a model to predict housing prices. The model will be deployed on an ongoing basis, to predict the price of a new house when a description is added to a website. Here are four features that could be used as predictors.
1. Size of the house (in square meters)
2. Average sales price... | # Fill in the line below with one of 1, 2, 3 or 4.
potential_leakage_feature = ____
# Check your answer
q_5.check()
#%%RM_IF(PROD)%%
potential_leakage_feature = 1
q_5.assert_check_failed()
#%%RM_IF(PROD)%%
potential_leakage_feature = 2
q_5.assert_check_passed()
#_COMMENT_IF(PROD)_
q_5.hint()
#_COMMENT_IF(PROD)_
q_5... | notebooks/ml_intermediate/raw/ex7.ipynb | Kaggle/learntools | apache-2.0 |
Data Preparation and Model Selection
Now we are ready to test the XGB approach, and will use confusion matrix and f1_score, which were imported, as metric for classification, as well as GridSearchCV, which is an excellent tool for parameter optimization. | import xgboost as xgb
X_train = training_data.drop(['Facies', 'Well Name','Formation','Depth'], axis = 1 )
Y_train = training_data['Facies' ] - 1
dtrain = xgb.DMatrix(X_train, Y_train)
train = X_train.copy()
train['Facies']=Y_train
train.head() | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
General Approach for Parameter Tuning
We are going to preform the steps as follows:
1.Choose a relatively high learning rate, e.g., 0.1. Usually somewhere between 0.05 and 0.3 should work for different problems.
2.Determine the optimum number of tress for this learning rate.XGBoost has a very usefull function called a... | from xgboost import XGBClassifier
xgb1 = XGBClassifier(
learning_rate = 0.1,
n_estimators=1000,
max_depth=5,
min_child_weight=1,
gamma = 0,
subsample=0.8,
colsample_bytree=0.8,
objective='multi:softmax',
nthread =4,
seed = 123,
)
modelfit(xgb1, train, features)
xgb1 | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Step 2: Tune max_depth and min_child_weight | from sklearn.model_selection import GridSearchCV
param_test1={
'max_depth':range(3,10,2),
'min_child_weight':range(1,6,2)
}
gs1 = GridSearchCV(xgb1,param_grid=param_test1,
scoring='accuracy', n_jobs=4,iid=False, cv=5)
gs1.fit(train[features],train[target])
gs1.grid_scores_, gs1.best_params_... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Step 3: Tune gamma | param_test3={
'gamma':[i/10.0 for i in range(0,5)]
}
gs3 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8,
gamma=0, learning_rate=0.1, max_delta_step=0, max_depth=9,
min_child_weight=1, n_estimators=370, nthread=4,
objective='multi:softprob', reg_alpha=0, reg_lambda=1,
... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Step 5: Tuning Regularization Parameters | param_test5={
'reg_alpha':[1e-5, 1e-2, 0.1, 1, 100]
}
gs5 = GridSearchCV(XGBClassifier(colsample_bylevel=1, colsample_bytree=0.8,
gamma=0.2, learning_rate=0.1, max_delta_step=0, max_depth=9,
min_child_weight=1, n_estimators=236, nthread=4,
objective='multi:softprob', reg_alpha=0, reg_lambda=1,... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Cross Validation
Next we use our tuned final model to do cross validation on the training data set. One of the wells will be used as test data and the rest will be the training data. Each iteration, a different well is chosen. | # Load data
filename = './facies_vectors.csv'
data = pd.read_csv(filename)
# Change to category data type
data['Well Name'] = data['Well Name'].astype('category')
data['Formation'] = data['Formation'].astype('category')
# Leave one well out for cross validation
well_names = data['Well Name'].unique()
f1=[]
for i in... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Model from all data set | # Load data
filename = './facies_vectors.csv'
data = pd.read_csv(filename)
# Change to category data type
data['Well Name'] = data['Well Name'].astype('category')
data['Formation'] = data['Formation'].astype('category')
# Split data for training and testing
X_train_all = data.drop(['Facies', 'Formation','Depth'], ax... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Use final model to predict the given test data set | # Load test data
test_data = pd.read_csv('validation_data_nofacies.csv')
test_data['Well Name'] = test_data['Well Name'].astype('category')
X_test = test_data.drop(['Formation', 'Well Name', 'Depth'], axis=1)
# Predict facies of unclassified data
Y_predicted = model_final.predict(X_test)
test_data['Facies'] = Y_predict... | HouMath/Face_classification_HouMath_XGB_03.ipynb | esa-as/2016-ml-contest | apache-2.0 |
Linear Regression
This is one of the simplest models to use, since it has uses linearly correlated data to 'predict' a value given | import pandas as pd
from sklearn import linear_model
import matplotlib.pyplot as plt | linear-regression/Linear-Regression.ipynb | morphean/deep-learning | apache-2.0 |
We will use pandas to handle reading of the data, pandas is pretty much the de facto standard for data manipulation in python. | df = pd.read_fwf('brain_body.txt')
x_values = df[['Brain']]
y_values = df[['Body']]
df.head() | linear-regression/Linear-Regression.ipynb | morphean/deep-learning | apache-2.0 |
now lets train the model using the data | import warnings
warnings.filterwarnings(action="ignore", module="scipy", message="^internal gelsd")
body_regression = linear_model.LinearRegression()
body_regression.fit(x_values, y_values)
fig = plt.figure()
plt.scatter(x_values, y_values)
plt.plot(x_values, body_regression.predict(x_values))
#add some axes and la... | linear-regression/Linear-Regression.ipynb | morphean/deep-learning | apache-2.0 |
Set up rotation matrices representing a 3-1-3 $(\psi,\theta,\phi)$ Euler angle set. | aCi = rotMat(3,psi)
cCa = rotMat(1,th)
bCc = rotMat(3,ph)
aCi,cCa,bCc
bCi = bCc*cCa*aCi; bCi #3-1-3 rotation
bCi_dot = difftotalmat(bCi,t,{th:thd,psi:psid,ph:phd});
bCi_dot | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
$\tilde{\omega} = {}^\mathcal{B}C^{\mathcal{I}} {}^\mathcal{B}{\dot{C}}^{\mathcal{I}}$ | omega_tilde = bCi*bCi_dot.T; omega_tilde | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
$\left[{}^\mathcal{I}\boldsymbol{\omega}^{\mathcal{B}}\right]\mathcal{B} = \left[ {}^\mathcal{B}C^{\mathcal{I}}{32} \quad {}^\mathcal{B}C^{\mathcal{I}}{13} \quad {}^\mathcal{B}C^{\mathcal{I}}{21} \right]$ | omega = simplify(Matrix([omega_tilde[2,1],omega_tilde[0,2],omega_tilde[1,0]]))
omega
w1,w2,w3 = symbols('omega_1,omega_2,omega_3')
s0 = solve(omega - Matrix([w1,w2,w3]),[psid,thd,phd]); s0 | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
Find EOM (second derivatives of Euler Angles) | I1,I2,I3 = symbols("I_1,I_2,I_3",real=True,positive=True)
iWb_B = omega
I_G_B = diag(I1,I2,I3)
I_G_B
diffmap = {th:thd,psi:psid,ph:phd,thd:thdd,psid:psidd,phd:phdd}
diffmap
t1 = I_G_B*difftotalmat(iWb_B,t,diffmap)
t2 = skew(iWb_B)*I_G_B*iWb_B
t1,t2
dh_G_B = t1+t2
dh_G_B
t3 = expand(dh_G_B[0]*cos(ph)*I2 - dh_G_B[1]... | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
Find initial orientation such that $\mathbf h$ is down-pointing | h = sqrt(((I_G_B*Matrix([w1,w2,w3])).transpose()*(I_G_B*Matrix([w1,w2,w3])))[0]);h
eqs1 = simplify(bCi.transpose()*I_G_B*Matrix([w1,w2,w3]) - Matrix([0,0,-h])); eqs1 #equal 0
simplify(solve(simplify(eqs1[0]*cos(psi) + eqs1[1]*sin(psi)),ph)) #phi solution
solve(simplify(expand(simplify(-eqs1[0]*sin(psi) + eqs1[1]*cos... | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
Generate MATLAB Code | out = codegen(("eom1",sol_psidd[0]), 'Octave', argument_sequence=[th,thd,psi,psid,ph,phd,I1,I2,I3]);out
codegen(("eom1",sol_thdd[0]), 'Octave', argument_sequence=[th,thd,psi,psid,ph,phd,I1,I2,I3])
codegen(("eom1",sol_phdd[0]), 'Octave', argument_sequence=[th,thd,psi,psid,ph,phd,I1,I2,I3,psidd])
codegen(("eom1",[s0[p... | Notebooks/Torque Free 3-1-3 Body Dynamics.ipynb | dsavransky/MAE4060 | mit |
Problem 3
Write a function that asks for an integer and prints the square of it. Use a while loop with a try,except, else block to account for incorrect inputs. | def ask():
while True:
try:
n = input('Input an integer: ')
except:
print 'An error occurred! Please try again!'
continue
else:
break
print 'Thank you, you number squared is: ',n**2
ask() | PythonBootCamp/Complete-Python-Bootcamp-master/Errors and Exceptions Homework - Solution.ipynb | yashdeeph709/Algorithms | apache-2.0 |
<h3>Calculation of the phosphor layer thickness of lanex regular given its areal density:</h3> | Dcell = 55*10**-6
DPET = 175*10**-6
Dcell2 = 13*10**-6
rhocell = 1.44*10**3
rhoPET = 1.38*10**3
rhophos = 4.48*10**3
sigma = 70*10**-2
Dphos = (sigma - Dcell*rhocell - DPET*rhoPET - Dcell2*rhocell)/rhophos
print(Dphos*10**6) | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
<h3>Define functions for photon density and photon current density</h3>
<font size="4"><p>These functions were derived from Fick's laws of diffusion:
$$ \frac{\partial n(z,t)}{\partial t} = D \frac{\partial^2 n(z,t)}{\partial z^2}, \: \: \phi (z,t) = -D \frac{\partial n(z,t)}{\partial z}$$
where n(z,t) is the photon de... | N0 = 10**6 #Number of photons emitted at t=0
lambdas = 2.85*10**-6 #Diffusion length in m
D = lambdas*c/6 #Diffusion constant
A = 100*10**-6*100*10**-6 #Area of segment in m^2
L = 81*10**-6 #Depth of lanex in m
l = 10.0*10**-6 #Distance from top lanex edge to segment in m
d = L-l #Distance from bottom lanex edge to seg... | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
<h3>Plot photon density</h3>
<font size="4"><p>The function $n(z,t)$ is calculated from 1 fs to 10 ps and plotted below. The boundary conditions are visibly satisfied and the function approaches a dirac delta function for short times. It then spreads out with the total number of photons decreasing as they're absorbed a... | narray = []
zarray = np.linspace(-l,d,1000)
time = [1,10,10**2,10**3,10**4]
time = np.multiply(time,10**-15) #convert to s
for i in range(len(time)):
narray.append([])
for z in zarray:
narray[i].append(n(z,time[i])*10**-6)
zarray = np.multiply(zarray,10**6)
#Update the matplotlib configuration parame... | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
<h3>Plot photon current density</h3>
<font size="4"><p>Photon current density is then calculated at $z=d$ and plotted below as a function of time.</font></p> | particlecurrentarray = []
tarray = []
for t in linspace(10**-15,50*10**-12,1000):
tarray.append(t*10**12)
particlecurrentarray.append(particlecurrent(t))
#Update the matplotlib configuration parameters
mpl.rcParams.update({'font.size': 18, 'font.family': 'serif'})
#Adjust figure size
plt.subplots(figsize=(12,... | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
<h3>Integrate photon current density</h3>
<font size="4"><p>The photon current density at $z=d$ is then integrated over large times and multiplied by the area $A$ to determine the total number of photons absorbed by the CCD. This is done numerically and analytically with the function defined below. A plot of the fracti... | Nabs = A*quad(particlecurrent,0,400*10**-12)[0] #Total number of photons absorbed at the boundary z=d
print(Nabs/N0)
def F(t,maxm,distance):
Sum1 = 0
Sum2 = 0
for m in range(-maxm,1):
am = distance-2*m*L
Sum1 += 1 - erf(am/sqrt(4*D*t))
for m in range(1,maxm+1):
am = distance-2*m... | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
<h3>Calculate number of photons absorbed as a function of d</h3>
<font size="4"><p>A function is defined to calculate the total number of photons absorbed at $z=d$ after all time as a function of $d$. The results are then plotted and found to be linear. The rather unpleasant expression defined above evidently can be ap... | FractionAbsArrayAnalytic = []
distancearray = []
#Find the fraction of photons absorbed at z=d for various values of d ranging from 0 to L - 1 um (to avoid division by zero errors)
for distance in linspace(0,L-10**-6,100):
Integrationtime = 10**-12
TargetError = 10**-3
Error = 1.0
FractionAbsAnalytic=0... | Photon_Diffusion/Photon_Diffusion.ipynb | drakero/Electron_Spectrometer | mit |
Tuning a scikit-learn estimator with skopt
Gilles Louppe, July 2016
Katie Malone, August 2016
Reformatted by Holger Nahrstaedt 2020
.. currentmodule:: skopt
If you are looking for a :obj:sklearn.model_selection.GridSearchCV replacement checkout
sphx_glr_auto_examples_sklearn-gridsearchcv-replacement.py instead.
Problem... | print(__doc__)
import numpy as np | dev/notebooks/auto_examples/hyperparameter-optimization.ipynb | scikit-optimize/scikit-optimize.github.io | bsd-3-clause |
Please change the pkg_path and model_file to be correct path | pkg_path = '../../python-package/'
model_file = 's3://my-bucket/xgb-demo/model/0002.model'
sys.path.insert(0, pkg_path)
import xgboost as xgb | xgboost-master/demo/distributed-training/plot_model.ipynb | RPGOne/Skynet | bsd-3-clause |
Plot the Feature Importance | # plot the first two trees.
bst = xgb.Booster(model_file=model_file)
xgb.plot_importance(bst) | xgboost-master/demo/distributed-training/plot_model.ipynb | RPGOne/Skynet | bsd-3-clause |
Plot the First Tree | tree_id = 0
xgb.to_graphviz(bst, tree_id) | xgboost-master/demo/distributed-training/plot_model.ipynb | RPGOne/Skynet | bsd-3-clause |
Model
We start with popular assumption that light is absorbed uniformly inside the device. The assumption can be justified for thin devices, and for white illumination. | def absorption(x):
return 1.5e28 | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
The base model consists in Poisson's equation coupled to the drift-diffusion equations for electrons and holes. Constant mobilities are assumed. Additionally, contacts can be defined as selective (blocking electrons and holes at "invalid" electrode"), or non-selective with local thermal equilibrium is assumed at any el... | def base_model(L=50e-9,selective=False,**kwargs):
model = models.BaseModel()
mesh = fvm.mesh1d(L)
models.std.bulk_heterojunction(model, mesh, absorption=absorption,selective_contacts=selective,**kwargs)
model.setUp()
return model | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
The basic model created by function above contains no recombination term, and must be suplemented with it. Complete models are created by functions below, with the following options for the recombination model:
- direct : $R=\beta \left(n p-n_i p_i \right)$
- Langevin: $R=\frac{\mu_n+\mu_p}{\varepsilon} \left(n p-n_i p... | def model_Langevin(**kwargs):
return base_model(langevin_recombination=True,**kwargs)
def model_const(**kwargs):
return base_model(const_recombination=True,**kwargs)
def model_SRH(**kwargs):
return base_model(const_recombination=True,srh_recombination=True,**kwargs) | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Below is a procedure generating default simulation parameters. They are parametrized by the bandgap, by the (symmetric) barrier at the electrodes, and by SRH lifetime. Note that not all parameters are used at the same time, for example SRH parameters are not used by non-SRH models. | def make_params(barrier=0.3,bandgap=1.2,srh_tau=1e-8):
params=models.std.bulk_heterojunction_params(barrier=barrier,bandgap=bandgap,Nc=1e27,Nv=1e27)
srh_trate=1e-8
params.update({
'beta':7.23e-17,
'electron.srh.trate':srh_trate,
'hole.srh.trate':srh_trate,
'srh.N0':1./(srh_ta... | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Calculations
The function below takes I_V curve, which should include points V=0 and J=0, and calculates the open circuit voltage, the power at maximum power point, and the fill factor. | def performance(v,J):
iv=scipy.interpolate.InterpolatedUnivariateSpline(v,J)
Isc=iv(0.)
Voc,=iv.roots()
v=np.linspace(0,Voc)
Pmax=np.amax(-v*iv(v))
Ff=-Pmax/(Voc*Isc)
return dict(Ff=Ff,Voc=Voc,Isc=Isc,Pmax=Pmax) | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
In the reference, the mobilities of electrons and holes are varied but kept equal. The following shows how such sweep can be implemented. | mu_values = np.logspace(-10,-2,19)
def mu_sweep(params):
for mu in mu_values:
p=dict(params)
p['electron.mu']=mu
p['hole.mu']=mu
yield mu,p
v_sweep = sweep('electrode0.voltage',np.linspace(0.,0.8,40)) | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Because different models are considered below, a common function is defined here to run the simulation and to plot the result. The function takes model as an argument. | def Voc_Ff(model,params):
c=context(model)
result=[]
def onemu(mu, cmu):
for _ in cmu.sweep(cmu.params, v_sweep):
pass
v,J=cmu.teval(v_sweep.parameter_name,'J')
p = performance(v,J)
return (mu, p['Voc'], p['Ff'])
result = np.asarray([onemu(*_) for _ in c.sweep... | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Results
Direct recombination, non-selective contacts
As seen below, in the case of direct recombination, selective contacts are useful for improving fill factor and open-circuit voltage regardless of mobilities. | Voc_Ff(model_const(selective=False),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Direct recombination, selective contacts | Voc_Ff(model_const(selective=True),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Langevin recombination, non-selective contants
If Langevin recombination is assumed, open circuit voltage drops regardless of contact selectivity. | Voc_Ff(model_Langevin(selective=False),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
Langevin recombination, selective contants | Voc_Ff(model_Langevin(selective=True),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
SRH recombination, non-selective contacts
The case of SRH recombination resembles the case of direct recombination in its dependence on mobility. This is not surprising, as in both cases the mobility does not enter the recombination term $R$. | Voc_Ff(model_SRH(selective=False),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
SRH recombination, selective contacts | Voc_Ff(model_SRH(selective=True),params); | examples/photovoltaic/Voc-Ff.ipynb | mzszym/oedes | agpl-3.0 |
This framework works with any other quantity we want to estimate. By changing sample_stat, you can compute the SE and CI for any sample statistic.
As an exercise, fill in sample_stat below with any of these statistics:
Standard deviation of the sample.
Coefficient of variation, which is the sample standard deviation ... | def sample_stat(sample):
# TODO: replace the following line with another sample statistic
return sample.mean()
slider = widgets.IntSliderWidget(min=10, max=1000, value=100)
interact(plot_sample_stats, n=slider, xlim=fixed([0, 100]))
None | jup_notebooks/data-science-ipython-notebooks-master/scipy/sampling.ipynb | steinam/teacher | mit |
Part Two
So far we have shown that if we know the actual distribution of the population, we can compute the sampling distribution for any sample statistic, and from that we can compute SE and CI.
But in real life we don't know the actual distribution of the population. If we did, we wouldn't need to estimate it!
In re... | class Resampler(object):
"""Represents a framework for computing sampling distributions."""
def __init__(self, sample, xlim=None):
"""Stores the actual sample."""
self.sample = sample
self.n = len(sample)
self.xlim = xlim
def resample(self):
"""Generates... | jup_notebooks/data-science-ipython-notebooks-master/scipy/sampling.ipynb | steinam/teacher | mit |
Exercise: write a new class called StdResampler that inherits from Resampler and overrides sample_stat so it computes the standard deviation of the resampled data. | class StdResampler(Resampler):
"""Computes the sampling distribution of the standard deviation."""
def sample_stat(self, sample):
"""Computes a sample statistic using the original sample or a
simulated sample.
"""
return sample.std() | jup_notebooks/data-science-ipython-notebooks-master/scipy/sampling.ipynb | steinam/teacher | mit |
When your StdResampler is working, you should be able to interact with it: | slider = widgets.IntSliderWidget(min=10, max=1000, value=100)
interact(plot_resampled_stats, n=slider)
None | jup_notebooks/data-science-ipython-notebooks-master/scipy/sampling.ipynb | steinam/teacher | mit |
Part Three
We can extend this framework to compute SE and CI for a difference in means.
For example, men are heavier than women on average. Here's the women's distribution again (from BRFSS data): | female_weight = scipy.stats.lognorm(0.23, 0, 70.8)
female_weight.mean(), female_weight.std() | jup_notebooks/data-science-ipython-notebooks-master/scipy/sampling.ipynb | steinam/teacher | mit |
This vectorization of operations simplifies the syntax of operating on arrays of data: we no longer have to worry about the size or shape of the array, but just about what operation we want done.
For arrays of strings, NumPy does not provide such simple access, and thus you're stuck using a more verbose loop syntax: | data = ['peter', 'Paul', 'MARY', 'gUIDO']
[s.capitalize() for s in data] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
This is perhaps sufficient to work with some data, but it will break if there are any missing values.
For example: | data = ['peter', 'Paul', None, 'MARY', 'gUIDO']
[s.capitalize() for s in data] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Pandas includes features to address both this need for vectorized string operations and for correctly handling missing data via the str attribute of Pandas Series and Index objects containing strings.
So, for example, suppose we create a Pandas Series with this data: | import pandas as pd
names = pd.Series(data)
names | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We can now call a single method that will capitalize all the entries, while skipping over any missing values: | names.str.capitalize() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Using tab completion on this str attribute will list all the vectorized string methods available to Pandas.
Tables of Pandas String Methods
If you have a good understanding of string manipulation in Python, most of Pandas string syntax is intuitive enough that it's probably sufficient to just list a table of available ... | monte = pd.Series(['Graham Chapman', 'John Cleese', 'Terry Gilliam',
'Eric Idle', 'Terry Jones', 'Michael Palin']) | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Methods similar to Python string methods
Nearly all Python's built-in string methods are mirrored by a Pandas vectorized string method. Here is a list of Pandas str methods that mirror Python string methods:
| | | | |
|-------------|------------------|-----... | monte.str.lower() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
But some others return numbers: | monte.str.len() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Or Boolean values: | monte.str.startswith('T') | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Still others return lists or other compound values for each element: | monte.str.split() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We'll see further manipulations of this kind of series-of-lists object as we continue our discussion.
Methods using regular expressions
In addition, there are several methods that accept regular expressions to examine the content of each string element, and follow some of the API conventions of Python's built-in re mod... | monte.str.extract('([A-Za-z]+)', expand=False) | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Or we can do something more complicated, like finding all names that start and end with a consonant, making use of the start-of-string (^) and end-of-string ($) regular expression characters: | monte.str.findall(r'^[^AEIOU].*[^aeiou]$') | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
The ability to concisely apply regular expressions across Series or Dataframe entries opens up many possibilities for analysis and cleaning of data.
Miscellaneous methods
Finally, there are some miscellaneous methods that enable other convenient operations:
| Method | Description |
|--------|-------------|
| get() | In... | monte.str[0:3] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Indexing via df.str.get(i) and df.str[i] is likewise similar.
These get() and slice() methods also let you access elements of arrays returned by split().
For example, to extract the last name of each entry, we can combine split() and get(): | monte.str.split().str.get(-1) | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Indicator variables
Another method that requires a bit of extra explanation is the get_dummies() method.
This is useful when your data has a column containing some sort of coded indicator.
For example, we might have a dataset that contains information in the form of codes, such as A="born in America," B="born in the Un... | full_monte = pd.DataFrame({'name': monte,
'info': ['B|C|D', 'B|D', 'A|C',
'B|D', 'B|C', 'B|C|D']})
full_monte | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
The get_dummies() routine lets you quickly split-out these indicator variables into a DataFrame: | full_monte['info'].str.get_dummies('|') | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
With these operations as building blocks, you can construct an endless range of string processing procedures when cleaning your data.
We won't dive further into these methods here, but I encourage you to read through "Working with Text Data" in the Pandas online documentation, or to refer to the resources listed in Fur... | # !curl -O http://openrecipes.s3.amazonaws.com/recipeitems-latest.json.gz
# !gunzip recipeitems-latest.json.gz | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
The database is in JSON format, so we will try pd.read_json to read it: | try:
recipes = pd.read_json('recipeitems-latest.json')
except ValueError as e:
print("ValueError:", e) | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Oops! We get a ValueError mentioning that there is "trailing data."
Searching for the text of this error on the Internet, it seems that it's due to using a file in which each line is itself a valid JSON, but the full file is not.
Let's check if this interpretation is true: | with open('recipeitems-latest.json') as f:
line = f.readline()
pd.read_json(line).shape | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Yes, apparently each line is a valid JSON, so we'll need to string them together.
One way we can do this is to actually construct a string representation containing all these JSON entries, and then load the whole thing with pd.read_json: | # read the entire file into a Python array
with open('recipeitems-latest.json', 'r') as f:
# Extract each line
data = (line.strip() for line in f)
# Reformat so each line is the element of a list
data_json = "[{0}]".format(','.join(data))
# read the result as a JSON
recipes = pd.read_json(data_json)
re... | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We see there are nearly 200,000 recipes, and 17 columns.
Let's take a look at one row to see what we have: | recipes.iloc[0] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
There is a lot of information there, but much of it is in a very messy form, as is typical of data scraped from the Web.
In particular, the ingredient list is in string format; we're going to have to carefully extract the information we're interested in.
Let's start by taking a closer look at the ingredients: | recipes.ingredients.str.len().describe() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
The ingredient lists average 250 characters long, with a minimum of 0 and a maximum of nearly 10,000 characters!
Just out of curiousity, let's see which recipe has the longest ingredient list: | recipes.name[np.argmax(recipes.ingredients.str.len())] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
That certainly looks like an involved recipe.
We can do other aggregate explorations; for example, let's see how many of the recipes are for breakfast food: | recipes.description.str.contains('[Bb]reakfast').sum() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Or how many of the recipes list cinnamon as an ingredient: | recipes.ingredients.str.contains('[Cc]innamon').sum() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We could even look to see whether any recipes misspell the ingredient as "cinamon": | recipes.ingredients.str.contains('[Cc]inamon').sum() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
This is the type of essential data exploration that is possible with Pandas string tools.
It is data munging like this that Python really excels at.
A simple recipe recommender
Let's go a bit further, and start working on a simple recipe recommendation system: given a list of ingredients, find a recipe that uses all th... | spice_list = ['salt', 'pepper', 'oregano', 'sage', 'parsley',
'rosemary', 'tarragon', 'thyme', 'paprika', 'cumin'] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We can then build a Boolean DataFrame consisting of True and False values, indicating whether this ingredient appears in the list: | import re
spice_df = pd.DataFrame(dict((spice, recipes.ingredients.str.contains(spice, re.IGNORECASE))
for spice in spice_list))
spice_df.head() | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
Now, as an example, let's say we'd like to find a recipe that uses parsley, paprika, and tarragon.
We can compute this very quickly using the query() method of DataFrames, discussed in High-Performance Pandas: eval() and query(): | selection = spice_df.query('parsley & paprika & tarragon')
len(selection) | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
We find only 10 recipes with this combination; let's use the index returned by this selection to discover the names of the recipes that have this combination: | recipes.name[selection.index] | jup_notebooks/data-science-ipython-notebooks-master/pandas/03.10-Working-With-Strings.ipynb | steinam/teacher | mit |
The X matrix correspond to the inputs and the Y matrix to the outputs to predict. | data = pd.read_csv('datasets/data_regression.csv')
X = data['X']
Y = data['Y']
# Normalization
X = np.asmatrix(normalize_pd(X)).T
Y = np.asmatrix(normalize_pd(Y)).T | src/Regression.ipynb | pvchaumier/ml_by_example | isc |
Linear regression
Here we have $\Phi(X) = X$. The function we look for has the form $f(x) = ax + b$. | def linear_regression(X, Y):
# Building the Phi matrix
Ones = np.ones((X.shape[0], 1))
phi_X = np.hstack((Ones, X))
# Calculating the weights
w = np.dot(np.dot(inv(np.dot(phi_X.T, phi_X)), phi_X.T), Y)
# Predicting the output values
Y_linear_reg = np.dot(phi_X, w)
return Y_linear_... | src/Regression.ipynb | pvchaumier/ml_by_example | isc |
The obtained solution does not represent the data very well. It is because the power of representation is too low compared to the target function. This is usually referred to as underfitting.
Polynomial Regression
Now, we approximate the target function by a polynom $f(x) = w_0 + w_1 x + w_2 x^2 + ... + w_d x^d$ with $... | def polynomial_regression(X, Y, degree):
# Building the Phi matrix
Ones = np.ones((X.shape[0], 1))
# Add a column of ones
phi_X = np.hstack((Ones, X))
# add a column of X elevated to all the powers from 2 to degree
for i in range(2, degree + 1):
# calculate the vector X to the power i a... | src/Regression.ipynb | pvchaumier/ml_by_example | isc |
The linear case is still underfitting but now, we see that the polynom of degree 20 is too sensitive to the data, especially around $[-2.5, -1.5]$. This phenomena is called overfitting: the model starts fitting the noise in the data as well and looses its capacity to generalize.
Regression with kernel gaussian
Lastly, ... | def gaussian_regression(X, Y, b, sigma, return_base=True):
"""b is the number of bases to use, sigma is the variance of the
base functions."""
# Building the Phi matrix
Ones = np.ones((X.shape[0], 1))
# Add a column of ones
phi_X = np.hstack((Ones, X))
# Choose randomly without rep... | src/Regression.ipynb | pvchaumier/ml_by_example | isc |
<header class="w3-container w3-teal">
<img src="images/utfsm.png" alt="" height="100px" align="left"/>
<img src="images/mat.png" alt="" height="100px" align="right"/>
</header>
<br/><br/><br/><br/><br/>
MAT281
Aplicaciones de la Matemática en la Ingeniería
Sebastián Flores
https://www.github.com/usantamaria/mat281
Clas... | %%bash
cat data/Challenger.txt | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Ejemplo 2D
Grafiquemos los datos | from matplotlib import pyplot as plt
import numpy as np
# Plot of data
data = np.loadtxt("data/Challenger.txt", skiprows=1)
x = data[:,0]
y = data[:,1]
plt.figure(figsize=(16,8))
plt.plot(x, y, 'bo', ms=8)
plt.title("Exito o Falla en lanzamiento de Challenger")
plt.xlabel(r"T [${}^o F$]")
plt.ylabel(r"Bad Rings")
plt.y... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Ejemplo 2D
Nos gustaría saber en qué condiciones se produce accidente. No nos importa el número de fallas, sólo si existe falla o no. | # Plot of data
data = np.loadtxt("data/Challenger.txt", skiprows=1)
x = (data[:,0]-32.)/1.8
y = np.array(data[:,1]==0,int)
plt.figure(figsize=(16,8))
plt.plot(x[y==0], y[y==0], 'bo', label="Falla", ms=8)
plt.plot(x[y>0], y[y>0], 'rs', label="Exito", ms=8)
plt.ylim([-0.1, 1.1])
plt.legend(loc=0, numpoints=1)
plt.title("... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Modelo
Definimos como
antes
$$\begin{aligned}
Y &= \begin{bmatrix}y^{(1)} \ y^{(2)} \ \vdots \ y^{(m)}\end{bmatrix}\end{aligned}$$
y
$$\begin{aligned}
X =
\begin{bmatrix}
1 & x^{(1)}_1 & \dots & x^{(1)}_n \
1 & x^{(2)}_1 & \dots & x^{(2)}_n \
\vdots & \vdots & & \vdots \
1 & x^{(m)}_1 & \dots & x^{(m)}_n \
\end{bmat... | from matplotlib import pyplot as plt
import numpy as np
def sigmoid(z):
return (1+np.exp(-z))**(-1.)
z = np.linspace(-5,5,100)
g = sigmoid(z)
fig = plt.figure(figsize=(16,8))
plt.plot(z,sigmoid(z), lw=2.0)
plt.plot(z,sigmoid(z*2), lw=2.0)
plt.plot(z,sigmoid(z-2), lw=2.0)
plt.grid("on")
plt.show() | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Modelo
Función Sigmoide
La función
sigmoide $g(z) = (1+e^{-z})^{-1}$ tiene la siguiente propiedad:
$$g'(z) = g(z)(1-g(z))$$
Modelo
Función Sigmoide
$g(z) = (1+e^{-z})^{-1}$ y $g'(z) = g(z)(1-g(z))$.
Demostración:
$$\begin{aligned}
g'(z) &= \frac{-1}{(1+e^{-z})^2} (-e^{-z}) \
&= \frac{e^{-z}}{(1+e^{-z})^2} \
... | from matplotlib import pyplot as plt
import numpy as np
def sigmoid(z):
return (1+np.exp(-z))**(-1.)
z = np.linspace(-5,5,100)
g = sigmoid(z)
dgdz = g*(1-g)
fig = plt.figure(figsize=(16,8))
plt.plot(z, g, "k", label="g(z)", lw=2)
plt.plot(z, dgdz, "r", label="dg(z)/dz", lw=2)
plt.legend()
plt.grid("on")
plt.show(... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Aproximación Ingenieril
¿Cómo podemos reutilizar lo que conocemos de regresión lineal?
Si buscamos minimizar
$$J(\theta) = \frac{1}{2} \sum_{i=1}^{m} \left( h_{\theta}(x^{(i)}) - y^{(i)}\right)^2$$
Podemos calcular el gradiente y luego utilizar el método del máximo
descenso para obtener $\theta$.
Aproximación Ingenieri... | import numpy as np
def sigmoid(z):
return 1./(1+np.exp(-z))
def norm2_error_logistic_regression(X, Y, theta0, tol=1E-6):
converged = False
alpha = 0.01/len(Y)
theta = theta0
while not converged:
H = sigmoid(np.dot(X, theta))
gradient = np.dot(X.T, (H-Y)*H*(1-H))
new_theta =... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Interpretación Probabilística
¿Es la derivación anterior
probabilísticamente correcta?
Asumamos que la pertenencia a los grupos está dado por
$$\begin{aligned}
\mathbb{P}[y = 1| \ x ; \theta ] & = h_\theta(x) \
\mathbb{P}[y = 0| \ x ; \theta ] & = 1 - h_\theta(x)\end{aligned}$$
Esto es, una distribución de Bernoulli co... | import numpy as np
def likelihood_logistic_regression(X, Y, theta0, tol=1E-6):
converged = False
alpha = 0.01/len(Y)
theta = theta0
while not converged:
H = sigmoid(np.dot(X, theta))
gradient = np.dot(X.T, H-Y)
new_theta = theta - alpha * gradient
converged = np.linalg.n... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Interpretación del resultado
¿Qué significa el parámetro obtenido $\theta$?
¿Cómo relacionamos la pertenencia a una clase (discreto) con la hipótesis $h_{\theta}(x)$ (continuo).
1. Aplicación a Datos del Challenger
Apliquemos lo anterior a los datos que tenemos del Challenger. | # Plot of data
data = np.loadtxt("data/Challenger.txt", skiprows=1)
x = (data[:,0]-32.)/1.8
X = np.array([np.ones(x.shape[0]), x]).T
y = np.array(data[:,1]==0,int)
theta_0 = y.mean() / X.mean(axis=0)
print "theta_0", theta_0
theta_J = norm2_error_logistic_regression(X, y, theta_0)
print "theta_J", theta_J
theta_l = lik... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
1. Aplicación a Datos del Challenger
Visualización de resultados | # Predictions
y_pred_J = sigmoid(np.dot(X, theta_J))
y_pred_l = sigmoid(np.dot(X, theta_l))
# Plot of data
plt.figure(figsize=(16,8))
plt.plot(x[y==0], y[y==0], 'bo', label="Falla", ms=8)
plt.plot(x[y>0], y[y>0], 'rs', label="Exito", ms=8)
plt.plot(x, y_pred_J, label="Norm 2 error prediction")
plt.plot(x, y_pred_l, lab... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
2. Aplicación al Iris Dataset
Hay
definidas $3$ clases, pero nosotros sólo podemos clasificar en $2$ clases. ¿Qué hacer? | import numpy as np
from sklearn import datasets
# Loading the data
iris = datasets.load_iris()
X = iris.data
Y = iris.target
print iris.target_names
# Print data and labels
for x, y in zip(X,Y):
print x, y | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
2. Aplicación al Iris Dataset
Podemos definir 2 clases: Iris Setosa y no Iris Setosa.
¿Que label le pondremos a cada clase? | import numpy as np
from sklearn import datasets
# Loading the data
iris = datasets.load_iris()
names = iris.target_names
print names
X = iris.data
Y = np.array(iris.target==0, int)
# Print data and labels
for x, y in zip(X,Y):
print x, y | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
2. Aplicación al Iris Dataset
Para aplicar el algoritmo, utilizando el algoritmo Logistic Regression de la librería sklearn, requerimos un código como el siguiente: | import numpy as np
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
# Loading the data
iris = datasets.load_iris()
names = iris.target_names
X = iris.data
Y = np.array(iris.target==0, int)
# Fitting the model
Logit = LogisticRegression()
Logit.fit(X,Y)
# Obtain the coefficients
print ... | clases/Unidad4-MachineLearning/Clase05-Clasificacion-RegresionLogistica/ClasificacionRegresionLogistica.ipynb | sebastiandres/mat281 | cc0-1.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.