markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Estimation
Load data: | data = sm.datasets.stackloss.load()
data.exog = sm.add_constant(data.exog) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Huber's T norm with the (default) median absolute deviation scaling | huber_t = sm.RLM(data.endog, data.exog, M=sm.robust.norms.HuberT())
hub_results = huber_t.fit()
print(hub_results.params)
print(hub_results.bse)
print(hub_results.summary(yname='y',
xname=['var_%d' % i for i in range(len(hub_results.params))])) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Huber's T norm with 'H2' covariance matrix | hub_results2 = huber_t.fit(cov="H2")
print(hub_results2.params)
print(hub_results2.bse) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Andrew's Wave norm with Huber's Proposal 2 scaling and 'H3' covariance matrix | andrew_mod = sm.RLM(data.endog, data.exog, M=sm.robust.norms.AndrewWave())
andrew_results = andrew_mod.fit(scale_est=sm.robust.scale.HuberScale(), cov="H3")
print('Parameters: ', andrew_results.params) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
See help(sm.RLM.fit) for more options and module sm.robust.scale for scale options
Comparing OLS and RLM
Artificial data with outliers: | nsample = 50
x1 = np.linspace(0, 20, nsample)
X = np.column_stack((x1, (x1-5)**2))
X = sm.add_constant(X)
sig = 0.3 # smaller error variance makes OLS<->RLM contrast bigger
beta = [5, 0.5, -0.0]
y_true2 = np.dot(X, beta)
y2 = y_true2 + sig*1. * np.random.normal(size=nsample)
y2[[39,41,43,45,48]] -= 5 # add some out... | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Example 1: quadratic function with linear truth
Note that the quadratic term in OLS regression will capture outlier effects. | res = sm.OLS(y2, X).fit()
print(res.params)
print(res.bse)
print(res.predict()) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Estimate RLM: | resrlm = sm.RLM(y2, X).fit()
print(resrlm.params)
print(resrlm.bse) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Draw a plot to compare OLS estimates to the robust estimates: | fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
ax.plot(x1, y2, 'o',label="data")
ax.plot(x1, y_true2, 'b-', label="True")
prstd, iv_l, iv_u = wls_prediction_std(res)
ax.plot(x1, res.fittedvalues, 'r-', label="OLS")
ax.plot(x1, iv_u, 'r--')
ax.plot(x1, iv_l, 'r--')
ax.plot(x1, resrlm.fittedvalues, 'g.-', lab... | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Example 2: linear function with linear truth
Fit a new OLS model using only the linear term and the constant: | X2 = X[:,[0,1]]
res2 = sm.OLS(y2, X2).fit()
print(res2.params)
print(res2.bse) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Estimate RLM: | resrlm2 = sm.RLM(y2, X2).fit()
print(resrlm2.params)
print(resrlm2.bse) | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
Draw a plot to compare OLS estimates to the robust estimates: | prstd, iv_l, iv_u = wls_prediction_std(res2)
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x1, y2, 'o', label="data")
ax.plot(x1, y_true2, 'b-', label="True")
ax.plot(x1, res2.fittedvalues, 'r-', label="OLS")
ax.plot(x1, iv_u, 'r--')
ax.plot(x1, iv_l, 'r--')
ax.plot(x1, resrlm2.fittedvalues, 'g.-', label="RLM")
legend... | examples/notebooks/robust_models_0.ipynb | yl565/statsmodels | bsd-3-clause |
The information about the class of each sample is stored in the target attribute of the dataset: | iris.target
iris.target_names
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
x_index = 3
y_index = 2
# this formatter will label the colorbar with the correct target names
formatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)])
plt.scatter(iris.data[:, x_index... | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
scikit-learn interface
All objects within scikit-learn share a uniform common basic API consisting of three complementary interfaces:
estimator interface for building and fitting models
predictor interface for making predictions
transformer interface for converting data.
The estimator interface is at the core of the ... | class Estimator(object):
def fit(self, X, y=None):
"""Fit model to data X (and y)"""
self.some_attribute = self.some_fitting_method(X, y)
return self
def predict(self, X_test):
"""Make prediction based on passed features"""
pred = self.make_prediction(X_te... | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
For a given scikit-learn estimator object named model, several methods are available. Irrespective of the type of estimator, there will be a fit method:
model.fit : fit training data. For supervised learning applications, this accepts two arguments: the data X and the labels y (e.g. model.fit(X, y)). For unsupervised ... | import pandas as pd
vlbw = pd.read_csv("../data/vlbw.csv", index_col=0)
subset = vlbw[['ivh', 'gest', 'bwt', 'delivery', 'inout',
'pltct', 'lowph', 'pneumo', 'twn', 'apg1']].dropna()
# Extract response variable
y = subset.ivh.replace({'absent':0, 'possible':1, 'definite':1})
# Standardize some varia... | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
We split the data into a training set and a testing set. By default, 25% of the data is reserved for testing. This is the first of multiple ways that we will see to do this. | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X0, y) | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
The LogisticRegression model in scikit-learn employs a regularization coefficient C, which defaults to 1. The amount of regularization is lower with larger values of C.
Regularization penalizes the values of regression coefficients, while smaller ones let the coefficients range widely. Scikit-learn includes two penalti... | from sklearn.linear_model import LogisticRegression
lrmod = LogisticRegression(C=1000)
lrmod.fit(X_train, y_train)
pred_train = lrmod.predict(X_train)
pred_test = lrmod.predict(X_test)
pd.crosstab(y_train, pred_train,
rownames=["Actual"], colnames=["Predicted"])
pd.crosstab(y_test, pred_test,
... | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
We can bootstrap some confidence intervals: | import numpy as np
n = 1000
boot_samples = np.empty((n, len(lrmod.coef_[0])))
for i in np.arange(n):
boot_ind = np.random.randint(0, len(X0), len(X0))
y_i, X_i = y.values[boot_ind], X0.values[boot_ind]
lrmod_i = LogisticRegression(C=1000)
lrmod_i.fit(X_i, y_i)
boot_samples[i] = lrmod_i.coef_... | notebooks/Scikit Learn.ipynb | fonnesbeck/scientific-python-workshop | cc0-1.0 |
Of course, that only predicts the value for a fraction of the data set. I don't think that I have made it entirely clear how to use cross-validation to get a prediction for the full training set, so let's do that now. We'll use Scikit-Learn's cross_val_predict. | from sklearn.model_selection import cross_val_predict
yCVpred = cross_val_predict(clf, X, y, cv=5) # Complete
fig = plt.figure(figsize=(6, 6))
plt.scatter(y,yCVpred)
plt.xlabel("Actual Value [x$1000]")
plt.ylabel("Predicted Value [x$1000]")
plt.show() | NeuralNetworks.ipynb | gtrichards/PHYS_T480 | mit |
Let's try to use the multi-layer perceptron classifier on the digits data set. We will use a single hidden layer to keep the training time reasonable. | %matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets, cross_validation, neural_network, svm, metrics
from sklearn.neural_network import MLPClassifier
digits = datasets.load_digits()
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, l... | NeuralNetworks.ipynb | gtrichards/PHYS_T480 | mit |
This looks pretty good! In general increasing the size of the hidden layer will improve performance at the cost of longer training time. Now try training networks with a hidden layer size of 5 to 20. At what point does performance stop improving? | from sklearn.model_selection import cross_val_score
hidden_size = np.arange(5,20)
scores = np.array([])
for sz in hidden_size:
classifier = MLPClassifier(solver='lbfgs', alpha=1e-5, random_state=0, hidden_layer_sizes=(sz,) )
#classifier.fit(data[:n_samples / 2], digits.target[:n_samples / 2])
scores = np.a... | NeuralNetworks.ipynb | gtrichards/PHYS_T480 | mit |
Our basic perceptron can do a pretty good job recognizing handwritten digits, assuming the digits are all centered in an 8x8 image. What happens if we embed the digit images at random locations within a 32x32 image? Try increasing the size of the hidden layer and see if we can improve the performance. | %matplotlib inline
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets, cross_validation, neural_network, svm, metrics
from sklearn.neural_network import MLPClassifier
digits = datasets.load_digits()
resize = 32 #Size of larger image to embed the digits
images_ex = np.zeros((digits.ta... | NeuralNetworks.ipynb | gtrichards/PHYS_T480 | mit |
Well that fell apart quickly! We're at roughly the point where neural networks faded from popularity in the 90s. Perceptrons generated intense interest because they were biologically inspired and could be applied generically to any supervised learning problem. However they weren't extensible to more realistic problems,... | from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
#Create a model
model = Sequential()
#Use two sparse layers to learn useful, translation-invariant features
model.add(Convolution2D(32,... | NeuralNetworks.ipynb | gtrichards/PHYS_T480 | mit |
2 - Dataset
You will use the same "Cat vs non-Cat" dataset as in "Logistic Regression as a Neural Network" (Assignment 2). The model you had built had 70% test accuracy on classifying cats vs non-cats images. Hopefully, your new model will perform a better!
Problem Statement: You are given a dataset ("data.h5") contain... | train_x_orig, train_y, test_x_orig, test_y, classes = load_data() | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
The following code will show you an image in the dataset. Feel free to change the index and re-run the cell multiple times to see other images. | # Example of a picture
index = 73
plt.imshow(train_x_orig[index])
print ("y = " + str(train_y[0,index]) + ". It's a " + classes[train_y[0,index]].decode("utf-8") + " picture.")
# Explore your dataset
m_train = train_x_orig.shape[0]
num_px = train_x_orig.shape[1]
m_test = test_x_orig.shape[0]
print ("Number of train... | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
As usual, you reshape and standardize the images before feeding them to the network. The code is given in the cell below.
<img src="images/imvectorkiank.png" style="width:450px;height:300px;">
<caption><center> <u>Figure 1</u>: Image to vector conversion. <br> </center></caption> | # Reshape the training and test examples
train_x_flatten = train_x_orig.reshape(train_x_orig.shape[0], -1).T # The "-1" makes reshape flatten the remaining dimensions
test_x_flatten = test_x_orig.reshape(test_x_orig.shape[0], -1).T
# Standardize data to have feature values between 0 and 1.
train_x = train_x_flatten... | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
$12,288$ equals $64 \times 64 \times 3$ which is the size of one reshaped image vector.
3 - Architecture of your model
Now that you are familiar with the dataset, it is time to build a deep neural network to distinguish cat images from non-cat images.
You will build two different models:
- A 2-layer neural network
- An... | ### CONSTANTS DEFINING THE MODEL ####
n_x = 12288 # num_px * num_px * 3
n_h = 7
n_y = 1
layers_dims = (n_x, n_h, n_y)
# GRADED FUNCTION: two_layer_model
def two_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):
"""
Implements a two-layer neural network: LINEA... | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Run the cell below to train your parameters. See if your model runs. The cost should be decreasing. It may take up to 5 minutes to run 2500 iterations. Check if the "Cost after iteration 0" matches the expected output below, if not click on the square (⬛) on the upper bar of the notebook to stop the cell and try to fin... | parameters = two_layer_model(train_x, train_y, layers_dims = (n_x, n_h, n_y), num_iterations = 2500, print_cost=True) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td> **Cost after iteration 0**</td>
<td> 0.6930497356599888 </td>
</tr>
<tr>
<td> **Cost after iteration 100**</td>
<td> 0.6464320953428849 </td>
</tr>
<tr>
<td> **...**</td>
<td> ... </td>
</tr>
<tr>
<td... | predictions_train = predict(train_x, train_y, parameters) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td> **Accuracy**</td>
<td> 1.0 </td>
</tr>
</table> | predictions_test = predict(test_x, test_y, parameters) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td> **Accuracy**</td>
<td> 0.72 </td>
</tr>
</table>
Note: You may notice that running the model on fewer iterations (say 1500) gives better accuracy on the test set. This is called "early stopping" and we will talk about it in the next course. Early stopping is ... | ### CONSTANTS ###
layers_dims = [12288, 20, 7, 5, 1] # 5-layer model
# GRADED FUNCTION: L_layer_model
def L_layer_model(X, Y, layers_dims, learning_rate = 0.0075, num_iterations = 3000, print_cost=False):#lr was 0.009
"""
Implements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.
Ar... | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
You will now train the model as a 5-layer neural network.
Run the cell below to train your model. The cost should decrease on every iteration. It may take up to 5 minutes to run 2500 iterations. Check if the "Cost after iteration 0" matches the expected output below, if not click on the square (⬛) on the upper bar of ... | parameters = L_layer_model(train_x, train_y, layers_dims, num_iterations = 2500, print_cost = True) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td> **Cost after iteration 0**</td>
<td> 0.771749 </td>
</tr>
<tr>
<td> **Cost after iteration 100**</td>
<td> 0.672053 </td>
</tr>
<tr>
<td> **...**</td>
<td> ... </td>
</tr>
<tr>
<td> **Cost after itera... | pred_train = predict(train_x, train_y, parameters) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
<table>
<tr>
<td>
**Train Accuracy**
</td>
<td>
0.985645933014
</td>
</tr>
</table> | pred_test = predict(test_x, test_y, parameters) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Expected Output:
<table>
<tr>
<td> **Test Accuracy**</td>
<td> 0.8 </td>
</tr>
</table>
Congrats! It seems that your 5-layer neural network has better performance (80%) than your 2-layer neural network (72%) on the same test set.
This is good performance for this task. Nice job!
Though in th... | print_mislabeled_images(classes, test_x, test_y, pred_test) | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
A few type of images the model tends to do poorly on include:
- Cat body in an unusual position
- Cat appears against a background of a similar color
- Unusual cat color and species
- Camera Angle
- Brightness of the picture
- Scale variation (cat is very large or small in image)
7) Test with your own image (optional... | ## START CODE HERE ##
my_image = "my_image.jpg" # change this to the name of your image file
my_label_y = [1] # the true class of your image (1 -> cat, 0 -> non-cat)
## END CODE HERE ##
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_... | deep-learnining-specialization/1. neural nets and deep learning/resources/Deep Neural Network - Application v3.ipynb | diegocavalca/Studies | cc0-1.0 |
Create fake "observations"
For the purposes of this tutorial, we'll a simplified version of the fake "observations" used in the Fitting 2 Paper Examples. We'll only use a Johnson:V light curve here and leave the PHOEBE parameters to their true values. We'll also use the spherical distortion method to speed up computati... | b = phoebe.default_binary()
b.set_value_all('distortion_method', 'sphere')
b.add_dataset('lc', passband='Johnson:V', dataset='mylcV')
b['sma@binary'] = 9.435
b['requiv@primary'] = 1.473
b['requiv@secondary'] = 0.937
b['incl@binary'] = 87.35
b['period@binary'] = 2.345678901
b['q@binary'] = 0.888
b['teff@primary'] = 63... | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's now add some correlated noise to the data, comprised of a Gaussian, exponential and quadratic term. This trend mimics instrumental noise and does not bear any astrophysical significance. It is still important we account for it, as it can affect the values of some astrophysical parameters we do care about (in this... | np.random.seed(1)
noiseV = 0.006 * np.exp( 0.4 + (t-t[0])/(t[-1]-t[0]) ) + np.random.normal(0.0, 0.003, len(t)) - 0.002*(t-t[0])**2/(t[-1]-t[0])**2 + 0.001*(t-t[0])/(t[-1]-t[0]) + 0.0002
noiseV -= np.mean(noiseV) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's also generate a noise model that resembles an astrophysical signal: for example, stellar pulsations, which we will represent with a sum of sine functions: | freqs = [1.97, 1.72, 2.98] # oscillation frequencies
amps = [0.034, 0.019, 0.019] # amplitudes
deltas = [0.16, 0.34, 0.86] # phase shifts
terms = [amps[i]*np.sin(2*np.pi*(freqs[i]*t)+deltas[i]) for i in [0,1,2]]
noiseV_puls = np.sum(terms, axis=0) + np.random.normal(0.0, 0.003, len(t))
fluxes = b.get_value('fluxes', ... | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Now we have some fake data with two types of noise suitable for modeling with GPs.
PHOEBE supports two different GP models: 'sklearn', which uses the GP implementation in scikit-learn, and celerite2. We have found that sklearn works better for instrumental noise, while celerite2 is designed with astrophysical noise in... | b['fluxes@mylcV@dataset'] = fluxes + noiseV
b['sigmas@mylcV@dataset'] = 0.003*np.ones_like(fluxes)
_ = b.plot(y='residuals', show=True) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
We can add a gaussian process kernel by only providing the GPs backend we want to use, in this case 'sklearn': | b.add_gaussian_process('sklearn')
print(b['gp_sklearn01']) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
The default sklearn kernel is 'white', which models, as the name suggests, white noise with a single 'noise_level' parameter. Let's see what the other options are: | b['kernel@gp_sklearn01'].choices | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
To see in more detail how each one of these works, refer to https://scikit-learn.org/stable/modules/gaussian_process.html#gp-kernels. For this trend, we have found that a sum of a DotProduct and RBF kernel works best (for how we arrived to this see the Fitting 2 Paper Automated GP Selection Example.
Let's switch the ke... | b['kernel@gp_sklearn01'] = 'dot_product'
b.add_gaussian_process('sklearn', kernel='rbf')
# set the parameters of the kernels to ones that model the noise trend closely
b.set_value('sigma_0', feature='gp_sklearn01', value=0.0198)
b.set_value('length_scale', feature='gp_sklearn02', value=71.0) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Sometimes, there may be some residuals in the eclipses due to the PHOEBE model not fitting the data well. GPs are very sensitive to these residuals and more often that not, will begin "stealing" signal from the PHOEBE model, rendering it useless. We can prevent this by masking out the points in the eclipse when running... | b['gp_exclude_phases@mylcV'] = [[-0.04,0.04], [-0.52,0.40]] | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Let's finally compute the model with GPs and plot the result: | b.run_compute(model='model_gps')
b.plot(s={'dataset': 0.005, 'model': 0.02}, ls={'model': '-'},
marker={'dataset': '.'},
legend=True)
b.plot(s={'dataset': 0.005, 'model': 0.02}, ls={'model': '-'},
marker={'dataset': '.'},
y='residuals',
legend=True, show=True) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
We can see that the GP model accounted for the correlated noise in our data, which in turn allows the PHOEBE model to fit the astrophysical signal more accurately.
Astrophysical noise: the celerite2 GPs backend
Let's now replace the observed fluxes with those with astrophysical noise and plot the residuals: | b['fluxes@mylcV@dataset'] = fluxes + noiseV_puls
b['sigmas@mylcV@dataset'] = 0.003*np.ones_like(fluxes)
_ = b.plot(model='latest', y='residuals', show=True) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
For this type of noise, a gaussian process kernel with the 'celerite2' backend on average works better than the 'sklearn' ExpSineSquared periodic kernel. We'll add two SHO kernels corresponding to the three frequencies used to generate the noise and approximate the other parameters. For a full description of each kerne... | b.add_gaussian_process('celerite2', kernel='sho', sigma=0.2, rho=1/1.97, tau=3)
b.add_gaussian_process('celerite2', kernel='sho', sigma=0.2, rho=1/1.72, tau=3)
b.add_gaussian_process('celerite2', kernel='sho', sigma=0.2, rho=1/2.98, tau=3)
b.run_compute() | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Uh-oh, we get an error! The issue is that we already have a sklearn kernel attached to our data and ss of yet, PHOEBE only supports one GPs "backend" at a time, either sklearn or celerite2. The two can't be mixed, however you can mix different kernels from the same module. So, let's disable the sklearn GP features befo... | b.disable_feature('gp_sklearn01')
b.disable_feature('gp_sklearn02')
b.run_compute(model='model_gps', overwrite=True)
b.plot(s={'dataset': 0.005, 'model': 0.02}, ls={'model': '-'},
marker={'dataset': '.'},
legend=True, show=True) | development/tutorials/gaussian_processes.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
You can inspect the content of the state using the following command. | def print_truncated_random_state():
"""To avoid spamming the outputs, print only part of the state."""
full_random_state = np.random.get_state()
print(str(full_random_state)[:460], '...')
print_truncated_random_state() | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
The state is updated by each call to a random function: | np.random.seed(0)
print_truncated_random_state()
_ = np.random.uniform()
print_truncated_random_state() | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
NumPy allows you to sample both individual numbers, or entire vectors of numbers in a single function call. For instance, you may sample a vector of 3 scalars from a uniform distribution by doing: | np.random.seed(0)
print(np.random.uniform(size=3)) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
NumPy provides a sequential equivalent guarantee, meaning that sampling N numbers in a row individually or sampling a vector of N numbers results in the same pseudo-random sequences: | np.random.seed(0)
print("individually:", np.stack([np.random.uniform() for _ in range(3)]))
np.random.seed(0)
print("all at once: ", np.random.uniform(size=3)) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
Random numbers in JAX
JAX's random number generation differs from NumPy's in important ways. The reason is that NumPy's PRNG design makes it hard to simultaneously guarantee a number of desirable properties for JAX, specifically that code must be:
reproducible,
parallelizable,
vectorisable.
We will discuss why in the... | import numpy as np
np.random.seed(0)
def bar(): return np.random.uniform()
def baz(): return np.random.uniform()
def foo(): return bar() + 2 * baz()
print(foo()) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
The function foo sums two scalars sampled from a uniform distribution.
The output of this code can only satisfy requirement #1 if we assume a specific order of execution for bar() and baz(), as native Python does.
This doesn't seem to be a major issue in NumPy, as it is already enforced by Python, but it becomes an iss... | from jax import random
key = random.PRNGKey(42)
print(key) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
A key is just an array of shape (2,).
'Random key' is essentially just another word for 'random seed'. However, instead of setting it once as in NumPy, any call of a random function in JAX requires a key to be specified. Random functions consume the key, but do not modify it. Feeding the same key to a random function w... | print(random.normal(key))
print(random.normal(key)) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
Note: Feeding the same key to different random functions can result in correlated outputs, which is generally undesirable.
The rule of thumb is: never reuse keys (unless you want identical outputs).
In order to generate different and independent samples, you must split() the key yourself whenever you want to call a ra... | print("old key", key)
new_key, subkey = random.split(key)
del key # The old key is discarded -- we must never use it again.
normal_sample = random.normal(subkey)
print(r" \---SPLIT --> new key ", new_key)
print(r" \--> new subkey", subkey, "--> normal", normal_sample)
del subkey # The subkey is also ... | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
split() is a deterministic function that converts one key into several independent (in the pseudorandomness sense) keys. We keep one of the outputs as the new_key, and can safely use the unique extra key (called subkey) as input into a random function, and then discard it forever.
If you wanted to get another sample fr... | key, subkey = random.split(key) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
which discards the old key automatically.
It's worth noting that split() can create as many keys as you need, not just 2: | key, *forty_two_subkeys = random.split(key, num=43) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
Another difference between NumPy's and JAX's random modules relates to the sequential equivalence guarantee mentioned above.
As in NumPy, JAX's random module also allows sampling of vectors of numbers.
However, JAX does not provide a sequential equivalence guarantee, because doing so would interfere with the vectorizat... | key = random.PRNGKey(42)
subkeys = random.split(key, 3)
sequence = np.stack([random.normal(subkey) for subkey in subkeys])
print("individually:", sequence)
key = random.PRNGKey(42)
print("all at once: ", random.normal(key, shape=(3,))) | docs/jax-101/05-random-numbers.ipynb | google/jax | apache-2.0 |
Prove manipolazioni array | unimatr = numpy.ones((10,10))
#unimatr
duimatr = unimatr*2
#duimatr
uniarray = numpy.ones((10,1))
#uniarray
triarray = uniarray*3
scalarray = numpy.arange(10)
scalarray = scalarray.reshape(10,1)
#NB fare il reshape da orizzontale a verticale è come se aggiungesse
#una dimensione all'array facendolo diventare un nda... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prove creazione matrice 3D con prodotti esterni | scalarray = numpy.arange(10)
uniarray = numpy.ones(10)
matricia = numpy.outer(scalarray, uniarray)
matricia
tensorio = numpy.outer(matricia,scalarray).reshape(10,10,10)
tensorio
# metodo di creazione array nd (numpy.ndarray) | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prove manipolazione matrici 3D numpy | tensorio = numpy.ones(1000).reshape(10,10,10)
tensorio
# metodo di creazione array nd (numpy.ndarray)
#altro metodo è con comando diretto
#tensorio = numpy.ndarray((3,3,3), dtype = int, buffer=numpy.arange(30))
#potrebbe essere utile con la matrice sparsa della peakmap, anche se difficilmente è maneggiabile come matric... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prove matrici sparse | from scipy import sparse
ramatricia = numpy.random.randint(2, size=25).reshape((5,5))
ramatricia
#efficiente per colonne
#sparsamatricia = sparse.csc_matrix(ramatricia)
#print(sparsamatricia)
#per righe
sparsamatricia = sparse.csr_matrix(ramatricia)
print(sparsamatricia)
sparsamatricia.toarray()
righe = numpy.arr... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prodotto di matrici
Prodotti interni
Considera di avere 2 matrici, a e b, in forma numpy array:
a*b fa il prodotto elemento per elemento (solo se a e b hanno stessa dimensione)
numpy.dot(a,b) fa il prodotto matriciale righe per colonne
Ora considera di avere 2 matrici, a e b, in forma di scipy.sparse:
a*b fa il prod... | #vari modi per fare prodotti di matrici (con somma con operatore + è lo stesso)
densamatricia = sparsamatricia.toarray()
#densa-densa
prodottoPerElementiDD = densamatricia*densamatricia
prodottoMatricialeDD = numpy.dot(densamatricia, densamatricia)
#sparsa-densa
prodottoMatricialeSD = sparsamatricia*densamatricia
pro... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prodotti esterni | densarray = numpy.array(["a","b"],dtype = object)
densarray2 = numpy.array(["c","d"],dtype = object)
numpy.outer(densarray,[1,2])
densamatricia = numpy.array([[1,2],[3,4]])
densamatricia2 = numpy.array([["a","b"],["c","d"]], dtype = object)
numpy.outer(densamatricia2,densamatricia).reshape(4,2,2)
densarray1 = numpy.... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Provo a passare operazioni a array con array di coordinate | matrice = numpy.arange(30).reshape(10,3)
matrice
righe = numpy.array([1,0,1,1])
colonne = numpy.array([2,0,2,2])
pesi = numpy.array([100,200,300,10])
print(righe,colonne)
matrice[righe,colonne]
matrice[righe,colonne] = (matrice[righe,colonne] + numpy.array([100,200,300,10]))
matrice
%matplotlib inline
a = pyplot.i... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Prove plots | from matplotlib import pyplot
%matplotlib inline
##AL MOMENTO INUTILE, NON COMPILARE
x = numpy.random.randint(10,size = 10)
y = numpy.random.randint(10,size = 10)
pyplot.scatter(x,y, s = 5)
#nb imshow si può fare solo con un 2d array
#visualizzazione di una matrice, solo matrici dense a quanto pare
a = pyplot.imshow... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Un esempio semplice del mio problema | import numpy
from scipy import sparse
import multiprocessing
from matplotlib import pyplot
#first i build a matrix of some x positions vs time datas in a sparse format
matrix = numpy.random.randint(2, size = 100).astype(float).reshape(10,10)
x = numpy.nonzero(matrix)[0]
times = numpy.nonzero(matrix)[1]
weights = numpy... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Confronti Debug! | #confronto con codice ORIGINALE in matlab
immagineOrig = scipy.io.loadmat('debugExamples/dbOrigResult.mat')['binh_df0']
a = pyplot.imshow(immagineOrig[:,0:80], aspect = 10)
pyplot.show()
#PROVA CON BINCOUNT
def mapIt(ithStep):
ncolumns = 80
image = numpy.zeros(ncolumns)
yTimed = y[ithStep]*times
posi... | codici/.ipynb_checkpoints/Prove numpy-checkpoint.ipynb | iurilarosa/thesis | gpl-3.0 |
Next we will build a set of x values from zero to 4π in increments of 0.1 radians to use in our plot. The x-values are stored in a numpy array. Numpy's arange() function has three arguments: start, stop, step. We start at zero, stop at 4π and step by 0.1 radians. Then we define a variable y as the sine of x using... | x = np.arange(0,4*np.pi,0.1) # start,stop,step
y = np.sin(x) | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
To create the plot, we use matplotlib's plt.plot() function. The two arguments are our numpy arrays x and y. The line plt.show() will show the finished plot. | plt.plot(x,y)
plt.show() | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
Next let's build a plot which shows two trig functions, sine and cosine. We will create the same two numpy arrays x and y as before, and add a third numpy array z which is the cosine of x. | x = np.arange(0,4*np.pi,0.1) # start,stop,step
y = np.sin(x)
z = np.cos(x) | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
To plot both sine and cosine on the same set of axies, we need to include two pair of x,y values in our plt.plot() arguments. The first pair is x,y. This corresponds to the sine function. The second pair is x,z. This correspons to the cosine function. If you try and only add three arguments as in plt.plot(x,y,z), your ... | plt.plot(x,y,x,z)
plt.show() | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
Let's build one more plot, a plot which shows the sine and cosine of x and also includes axis labels, a title and a legend. We build the numpy arrays using the trig functions as before: | x = np.arange(0,4*np.pi-1,0.1) # start,stop,step
y = np.sin(x)
z = np.cos(x) | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
The plt.plot() call is the same as before using two pairs of x and y values. To add axis labels we will use the following methods:
| matplotlib method | description | example |
| ----------------- | ----------- | ------- |
| plt.xlabel() | x-axis label | plt.xlabel('x values from 0 to 4pi') |
| plt.ylabel() | y-axis la... | plt.plot(x,y,x,z)
plt.xlabel('x values from 0 to 4pi') # string must be enclosed with quotes ' '
plt.ylabel('sin(x) and cos(x)')
plt.title('Plot of sin and cos from 0 to 4pi')
plt.legend(['sin(x)', 'cos(x)']) # legend entries as seperate strings in a list
plt.show() | content/code/matplotlib_plots/plotting_trig_functions.ipynb | ProfessorKazarinoff/staticsite | gpl-3.0 |
code,代码
name,名称
industry,所属行业
area,地区
pe,市盈率
outstanding,流通股本(亿)
totals,总股本(亿)
totalAssets,总资产(万)
liquidAssets,流动资产
fixedAssets,固定资产
reserved,公积金
reservedPerShare,每股公积金
esp,每股收益
bvps,每股净资
pb,市净率
timeToMarket,上市日期
undp,未分利润
perundp, 每股未分配
rev,收入同比(%)
profit,利润同比(%)
gpr,毛利率(%)
npr,净利润率(%)
holders,股东人数
['name', 'pe', 'out... | col_show = ['name', 'open', 'pre_close', 'price', 'high', 'low', 'volume', 'amount', 'time', 'code']
initial_letter = ['HTGD','OFKJ','CDKJ','ZJXC','GXKJ','FHTX','DZJG']
code =[]
for letter in initial_letter:
code.append(df[df['UP']==letter].code[0])
#print(code)
if code != '': #not empty != ''
df_price = t... | sample_code/date_utils.ipynb | yunfeiz/py_learnt | apache-2.0 |
TO-DO
Add the map from initial to code
build up a dataframe with fundamental and indicotors
For Leadings, need cache more data for the begining data | from matplotlib.mlab import csv2rec
df=ts.get_k_data("002456",start='2018-01-05',end='2018-01-09')
df.to_csv("temp.csv")
r=csv2rec("temp.csv")
#r.date
import time, datetime
#str = df[df.code == '600487'][clommun_show].name.values
#print(str)
today=datetime.date.today()
yesterday = today - datetime.timedelta(1)
#prin... | sample_code/date_utils.ipynb | yunfeiz/py_learnt | apache-2.0 |
(1024, 3)
行列数都与我们爬取到的数量一致,通过。
分词
下面我们需要做一件重要工作——分词
我们首先调用jieba分词包。
我们此次需要处理的,不是单一文本数据,而是1000多条文本数据,因此我们需要把这项工作并行化。这就需要首先编写一个函数,处理单一文本的分词。
有了这个函数之后,我们就可以不断调用它来批量处理数据框里面的全部文本(正文)信息了。你当然可以自己写个循环来做这项工作。但这里我们使用更为高效的apply函数。如果你对这个函数有兴趣,可以点击这段教学视频查看具体的介绍。
下面这一段代码执行起来,可能需要一小段时间。请耐心等候。 | import jieba
def chinese_word_cut(mytext):
return " ".join(jieba.cut(mytext))
df["content_cutted"] = df.content.apply(chinese_word_cut)
#执行完毕之后,我们需要查看一下,文本是否已经被正确分词。
df.content_cutted.head()
#文本向量化
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
n_features = 1000
tf_vectorizer = Count... | jupyter_notebook/datascience.ipynb | xiaoxiaoyao/MyApp | unlicense |
我们需要人为设定主题的数量。这个要求让很多人大跌眼镜——我怎么知道这一堆文章里面多少主题?!
别着急。应用LDA方法,指定(或者叫瞎猜)主题个数是必须的。如果你只需要把文章粗略划分成几个大类,就可以把数字设定小一些;相反,如果你希望能够识别出非常细分的主题,就增大主题个数。
对划分的结果,如果你觉得不够满意,可以通过继续迭代,调整主题数量来优化。
这里我们先设定为5个分类试试。 | #应用LDA方法
from sklearn.decomposition import LatentDirichletAllocation
n_topics = 5
lda = LatentDirichletAllocation(n_topics=n_topics, max_iter=50,
learning_method='online',
learning_offset=50.,
random_state=0)
#这一部分工作量较大,程序会... | jupyter_notebook/datascience.ipynb | xiaoxiaoyao/MyApp | unlicense |
到这里,LDA已经成功帮我们完成了主题抽取。但是我知道你不是很满意,因为结果不够直观。
那咱们就让它直观一些好了。
执行以下命令,会有有趣的事情发生。 | import pyLDAvis
import pyLDAvis.sklearn
pyLDAvis.enable_notebook()
pyLDAvis.sklearn.prepare(lda, tf, tf_vectorizer) | jupyter_notebook/datascience.ipynb | xiaoxiaoyao/MyApp | unlicense |
Load data | lastnode = 5000
datafile = open('/var/datasets/wdc/small-pld-arc')
G = nx.DiGraph()
for line in datafile:
ijstr = line.split('\t')
i=int(ijstr[0])
j=int(ijstr[1])
if i>lastnode:
break
if j>lastnode:
continue
G.add_edge(i,j)
datafile.close()
Gorig = G.copy()
ind... | randomwalks/WDC Random Walk.ipynb | mitliagkas/graphs | mit |
Convert to Javascript for interactivity
Adapted from:
http://nbviewer.ipython.org/github/ipython-books/cookbook-code/blob/master/notebooks/chapter06_viz/04_d3.ipynb
From:
http://networkx.github.io/documentation/latest/examples/javascript/force.html | #from IPython.core.display import display_javascript
import json
from networkx.readwrite import json_graph
d = json_graph.node_link_data(G)
for node in d['nodes']:
node['name']=node['id']
node['value']=G.degree(node['id'])
if True:
node['group'] = node['id'] % 4
else:
if node['id']<10:
... | randomwalks/WDC Random Walk.ipynb | mitliagkas/graphs | mit |
Uses:
https://github.com/mbostock/d3/wiki/Force-Layout
http://bl.ocks.org/mbostock/4062045 | Javascript(filename='force.js')
L = nx.linalg.laplacianmatrix.directed_laplacian_matrix(G)
Linv = np.linalg.inv(L)
L.shape
n = L.shape[0]
Reff = np.zeros((n,n))
Gsparse = G.copy()
graphcleanup(Gsparse)
nodelookup={Gsparse.nodes()[idx]:idx for idx in range(len(Gsparse.nodes()))}
edge = np.zeros((n,1))
for (i,j) i... | randomwalks/WDC Random Walk.ipynb | mitliagkas/graphs | mit |
If you call
arr.argsort()[:3]
It will give you the indices of the 3 smallest elements.
array([0, 2, 1], dtype=int64)
So, for n, you should call
arr.argsort()[:n] | res = ReffAbs.reshape(n**2)
argp = np.argpartition(res,n**2-n)
mask = (ReffAbs < res[argp[-int(0.5*Gsparse.number_of_nodes())]]) & (ReffAbs >0)
for (i,j) in Gsparse.edges():
if mask[nodelookup[i],nodelookup[j]]:
Gsparse.remove_edge(i,j)
cleanupgraph(Gsparse)
d = json_graph.node_link_data(Gsparse)
for nod... | randomwalks/WDC Random Walk.ipynb | mitliagkas/graphs | mit |
Check if there are missing values. | # for col in varsom_df.columns.values:
# print(f'{col}: {varsom_df[col].unique()} \n')
# Find the amount of NaN values in each column
print(varsom_df.isnull().sum().sort_values(ascending=False)) | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Fill missing values where necessary. | varsom_df['mountain_weather_wind_speed'] = varsom_df['mountain_weather_wind_speed'].fillna('None')
varsom_df['mountain_weather_wind_direction'] = varsom_df['mountain_weather_wind_direction'].fillna('None')
print(varsom_df.isnull().sum().sort_values(ascending=False)) | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Feature engineering
Re-label og -classifiy variables where necessary.
Add an avalanche problem severity index - based on its attributes size, distribution and sensitivity.
When using shift or filling values using mean or similar, make sure to first sort individual regions and seasons by date. | varsom_df['date'] = pd.to_datetime(varsom_df['date_valid'], infer_datetime_format=True)
def add_prevday_features(df):
### danger level
df['danger_level_prev1day'] = df['danger_level'].shift(1)
df['danger_level_name_prev1day'] = df['danger_level_name'].shift(1)
df['danger_level_prev2day'] = df['danger_l... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Add historical values, e.g. yesterdays precipitation
Add a tag to the feature name to indicate if it is categorical (c) or numerical (n).
Add a target tag (t).
Add a modelled (m) or observed (o) tag.
_prev1day
_prev3day
n_f_Next24HourChangeInTempFromPrev3DayMax - change of temperature over a certain period.
n_r_Prev7da... | # Check if sensitivity transformation worked...
print(varsom_df['avalanche_problem_1_sensitivity_id_class'].value_counts())
varsom_df.filter(['mountain_weather_precip_region', 'mountain_weather_precip_region_prev3daysum']).head(12)
varsom_df[varsom_df['region_id']==3012].filter(['region_id', 'danger_level', 'danger_l... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Combine avalanche problem attributes into single parameter | def get_aval_problem_combined(type_, dist_, sens_, size_):
return int("{0}{1}{2}{3}".format(type_, dist_, sens_, size_))
def print_aval_problem_combined(aval_combined_int):
aval_combined_str = str(aval_combined_int)
#with open(aps_pth / r'aps/config/snoskred_keys.json') as jdata:
with open(r'D:\Dev\AP... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Hot encode categorical variables where necessary. | # hot encode
hot_encode_ = ['emergency_warning', 'author', 'mountain_weather_wind_direction']
varsom_df = pd.get_dummies(varsom_df, columns=hot_encode_) | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Check if there are no weired or missing values. | # Check if there are no weired or missing values.
for col in varsom_df.columns.values:
print(f'{col}: {varsom_df[col].unique()} \n') | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Remove variables we know we do not need. In this case mainly because they are redundant like the avalanche_problem_1_ext_name and avalanche_problem_1_ext_id - in this case we only keep the numeric id variable. | del_list = [
'utm_zone',
'utm_east',
'utm_north',
'danger_level_name',
'avalanche_problem_1_exposed_height_fill',
'avalanche_problem_2_exposed_height_fill',
'avalanche_problem_3_exposed_height_fill',
'avalanche_problem_1_valid_expositions',
'avalanche_problem_2_valid_expositions',
... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Fill missing values where necessary | fill_list = [
'mountain_weather_freezing_level',
'mountain_weather_precip_region',
'mountain_weather_precip_region_prev1day',
'mountain_weather_precip_region_prev3daysum',
'mountain_weather_precip_most_exposed',
'mountain_weather_precip_most_exposed_prev1day',
'mountain_weather_temperature_m... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Eventually remove variables with many missing values. | del_list = [
'danger_level_name_prev1day', 'danger_level_name_prev2day', 'danger_level_name_prev3day',
'mountain_weather_change_wind_direction',
'mountain_weather_change_hour_of_day_start',
'mountain_weather_change_hour_of_day_stop',
'mountain_weather_change_wind_speed',
'mountain_weather_fl_hou... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Check again if there are still values missing...
need to replace these Nans with meaningful values or remove the feature. | # Find the amount of NaN values in each column
print(varsom_df.isnull().sum().sort_values(ascending=False))
# Compute the correlation matrix - works only on numerical variables.
corr = varsom_df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] ... | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
We can see that some parameters are highly correlated. These are mainly the parameters belonging to the same avalanche problem. Depending on the ML algorithm we use we have to remove some of them. | #corr['avalanche_problem_1_cause_id'].sort_values(ascending=False)
#corr
#sns.pairplot(varsom_df.drop(['date_valid'], axis=1))
# Get all numerical features
num_feat = varsom_df._get_numeric_data().columns
num_feat
# let's see the details about remainig variables
varsom_df.describe() | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
Save data for further analysis | varsom_df.to_csv('varsom_ml_preproc_3y.csv', index_label='index') | aps/notebooks/ml_varsom/preprocessing.ipynb | kmunve/APS | mit |
<table align="left">
<td>
<a href="https://github.com/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb">
<img src="https://cloud.google.com/ml-engine/images/github-logo-32px.png" alt="GitHub logo">
View on GitHub
</a>
</td>
</table>
... | %%writefile requirements.txt
joblib~=1.0
numpy~=1.20
scikit-learn~=0.24
google-cloud-storage>=1.26.0,<2.0.0dev
# Required in Docker serving container
%pip install -U --user -r requirements.txt
# For local FastAPI development and running
%pip install -U --user "uvicorn[standard]>=0.12.0,<0.14.0" fastapi~=0.63
# Verte... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Before you begin
Set up your Google Cloud project
The following steps are required, regardless of your notebook environment.
Select or create a Google Cloud project. When you first create an account, you get a $300 free credit towards your compute/storage costs.
Make sure that billing is enabled for your project.
... | # Get your Google Cloud project ID from gcloud
shell_output=!gcloud config list --format 'value(core.project)' 2>/dev/null
try:
PROJECT_ID = shell_output[0]
except IndexError:
PROJECT_ID = None
print("Project ID:", PROJECT_ID) | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Authenticate your Google Cloud account
If you are using Google Cloud Notebooks, your environment is already
authenticated. Skip this step.
If you are using Colab, run the cell below and follow the instructions
when prompted to authenticate your account via oAuth.
Otherwise, follow these steps:
In the Cloud Console, g... | import os
import sys
# If you are running this notebook in Colab, run this cell and follow the
# instructions to authenticate your GCP account. This provides access to your
# Cloud Storage bucket and lets you submit training jobs and prediction
# requests.
# If on Google Cloud Notebooks, then don't execute this code
... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Configure project and resource names | REGION = "us-central1" # @param {type:"string"}
MODEL_ARTIFACT_DIR = "custom-container-prediction-model" # @param {type:"string"}
REPOSITORY = "custom-container-prediction" # @param {type:"string"}
IMAGE = "sklearn-fastapi-server" # @param {type:"string"}
MODEL_DISPLAY_NAME = "sklearn-custom-container" # @param {t... | notebooks/community/sdk/SDK_Custom_Container_Prediction.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.