markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
ArraysThere are several kinds of sequences in Python. A [list](lists) is one. However, the sequence type that we will use most in the class, is the array.The `numpy` package, abbreviated `np` in programs, provides Python programmerswith convenient and powerful functions for creating and manipulating arrays. | # Load the numpy package, and call it "np".
import numpy as np | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
Creating arrays The `array` function from the Numpy package creates an array from single values, or sequences of values.For example, remember `my_list`? | my_list = [1, 2, 3] | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
This is a `list`: | type(my_list) | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
The `array` function from Numpy can make an array from this list: | my_array = np.array(my_list)
my_array | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
As you can see from the display above, this is an array. We confirm it with `type`: | type(my_array) | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
We can also create the list and then the array in one call, like this: | my_array = np.array([1, 2, 3])
my_array | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
Here `[1, 2, 3]` is an *expression* that returns a list. `np.array` then operates on the returned list, to create an array.Arrays often contain numbers, but, like lists, they can also contain stringsor other types of values. However, a single array can only contain a singlekind of data. (It usually doesn't make sense ... | english_parts_of_speech = np.array(["noun", "pronoun", "verb", "adverb", "adjective", "conjunction", "preposition", "interjection"])
english_parts_of_speech | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
We have not seen this yet, but Python allows us to spread expressions betweenround and square brackets across many lines. It knows that the expression hasnot finished yet because it is waiting for the closing bracket. For example, this cell works in the exactly the same way as the cell above, and may be easier to rea... | # An expression between brackets spread across many lines.
english_parts_of_speech = np.array(
["noun",
"pronoun",
"verb",
"adverb",
"adjective",
"conjunction",
"preposition",
"interjection"]
)
english_parts_of_speech | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
Below, we collect four different temperatures into a list called `temps`.These are the [estimated average daily hightemperatures](http://berkeleyearth.lbl.gov/regions/global-land) over all landon Earth (in degrees Celsius) for the decades surrounding 1850, 1900, 1950,and 2000, respectively, expressed as deviations from... | baseline_high = 14.48
highs = np.array([baseline_high - 0.880,
baseline_high - 0.093,
baseline_high + 0.105,
baseline_high + 0.684])
highs | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
Calculations with arrays Arrays can be used in arithmetic expressions to compute over their contents.When an array is combined with a single number, that number is combined witheach element of the array. Therefore, we can convert all of these temperaturesto Fahrenheit by writing the familiar conversion formula. | (9/5) * highs + 32 | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
As we saw for strings, arrays have *methods*, which are functions thatoperate on the array values. The `mean` of a collection of numbers is itsaverage value: the sum divided by the length. Each pair of parentheses in theexamples below is part of a call expression; it's calling a function with noarguments to perform a ... | # The number of elements in the array
highs.size
highs.sum()
highs.mean() | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
Functions on Arrays Numpy provides various useful functions for operating on arrays.For example, the `diff` function computes the difference between each adjacentpair of elements in an array. The first element of the `diff` is the secondelement minus the first. | np.diff(highs) | _____no_output_____ | CC-BY-4.0 | ipynb/03/Arrays.ipynb | matthew-brett/cfd-uob |
cat1 - cat116 are categorical | categorical_vars = ['cat{}'.format(i+1) for i in range(116)]
for var in categorical_vars:
train = pd.get_dummies(train, columns=[var])
train.head()
def multi_model_prediction(test_df, models):
preds = list()
for model in models:
preds.append(model.predict(test_df))
return [np.mean(p) for p in np... | _____no_output_____ | MIT | allstate/10-21-2016 Tate .ipynb | nkwan12/kaggle-competitions |
Stack Analysis | # The Implementation #
# Additional Questions to Address #
**Difference Between Class and Struct:**
**Public and Private:**
**size_t:**
**Where'd all the Pointers go?:** | _____no_output_____ | MIT | Stack.ipynb | chapman-cs510-2017f/cw-12-evan_logan_tim |
**new and delete:** new is a keyword for creating a new instance of an object, delete is the keyword to free up the data allocated for a given instance of an object. The equivalent in C is free(obj) instead of delete and calloc() in C would be a similar memory allocation method for the keyword new. | **Memory Leaks:**
**unique_ptr:** This mimics the action of a "garbage collector", ie it will delete any unused memory blocks.
**List Initializer:**
**Rule of Zero:** | _____no_output_____ | MIT | Stack.ipynb | chapman-cs510-2017f/cw-12-evan_logan_tim |
Checkpoint 2 | # imports.
from datetime import datetime
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from scipy import integrate
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import random
plt.rcParams['figure.figsize'] = (10, 6)
plt.rcParams['font.size'] = 16
# Constants
G = 6.67408... | _____no_output_____ | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Initial ConditionsBelow are the initial positions and velocities for Earth and Mars. | # positions and velocities at t=0 (2019/6/2)
rs = [[-4.8957151e10, -1.4359284e11, 501896.65], # Earth
[-1.1742901e11, 2.1375285e11, 7.3558899e9]] # Mars (units of m)
vs = [[27712., -9730., -0.64148], # Earth
[-20333., -9601., 300.34]] # Mars (units of m/s) | _____no_output_____ | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Historical PositionsBelow are historical positions for Earth and Mars at t=-1000 days prior to 2019/6/2. These will be used in tasks 5 and 6. | # positions of the planets at (2019/6/2)-1000 days
rspast = [[1.44109e11, -4.45267e10, -509142.], # Earth
[1.11393e11, -1.77611e11, -6.45385e9]] # Mars | _____no_output_____ | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Earth/Mars functionsBelow are functions for the equations of motion (the vector of 1st derivtives) for Earth and Mars and for calculating the angle between Earth and Mars. | def earth_mars_motion(t, y):
"""
# order of variables
# 0,1,2 rx,ry,rz for Earth
# 3,4,5 rx,ry,rz for Mars
# 6,7,8 vx,vy,vz for Earth
# 9,10,11 vx,vy,vz for Mars
# order of derivatives:
# 0,1,2 Drx,Dry,Drz for Earth
# 3,4,5 Drx,Dry,Drz for Mars
# 6,7,8 Dvx,Dvy,Dvz for Earth
... | _____no_output_____ | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 1Write a code that solves the equations and plots trajectories of Mars and Earth up to some $t_{max}$. The 3D plot should include at least one full orbit for each body. | # setting time domain.
tmax = 8000*day2sec # 8000 days.
dt = 3600 # 1 hour.
ts = np.arange(0, tmax, dt)
trange = (ts[0], ts[-1])
def get_traj(initial_rs, initial_vs):
ini = np.append(initial_rs, initial_vs) # initial coordinates of Earth and Mars
sol = integrate.solve_ivp(earth_mars_motion, trange, ini, me... | /Users/callum/.conda/envs/coding/lib/python3.7/site-packages/IPython/core/pylabtools.py:128: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
fig.canvas.print_figure(bytes_io, **kw)
| MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 2Find the time of the next opposition to $\pm10$ days. Return the time in days from $t_0$ = 2 June 2019. | def get_opp_times(solutions, times):
thetas = angle_between_planets(solutions)
# finding relationship between neighbouring points.
thetas_diff = np.diff(thetas)
# determining locations of minima.
indices = np.where(np.sign(thetas_diff[:-1]) < np.sign(thetas_diff[1:]))[0] + 1
# recording times th... | Next opposition in [ 500.25 1285.75 2056. 2820.875 3585.875
4356.29166667 5142.08333333 5952.45833333 6748.08333333 7522.58333333] days.
| MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 3Find the times for 10 oppositions in days since 2 June 2019. The results must be accurate to 1 day. Convert this to dates (year/month/day) and print out on the screen. Do not worry if the dates come out different than the actual dates you can find online, it’s supposed to be like that.The `calculate_oppositions`... | def get_opp_times(solutions, times):
thetas = angle_between_planets(solutions)
# finding relationship between neighbouring points
thetas_diff = np.diff(thetas)
# determining locations of minima
indices = np.where(np.sign(thetas_diff[:-1]) < np.sign(thetas_diff[1:]))[0] + 1
# recording times thes... | t = 500.25 day: 2020-10-14 06:00:00
t = 1285.75 day: 2022-12-08 17:00:00
t = 2056.00 day: 2025-01-16 23:00:00
t = 2820.88 day: 2027-02-20 20:00:00
t = 3585.88 day: 2029-03-26 21:00:00
t = 4356.29 day: 2031-05-06 07:00:00
t = 5142.08 day: 2033-06-30 02:00:00
t = 5952.46 day: 2035-09-18 11:00:00
t = 6748.08 day: 2037-11-... | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 4Estimate standard errors of these times assuming that all initial positions and velocities (12 numbers) are normally distributed random numbers with means as specified in the list of parameters, and coefficients of variation (standard deviation divided by the mean) equal to 3x10$^{-5}$.The `estimate_errors` func... | # gaussian sampling function.
def get_sample(arr):
arr = np.array(arr)
sample = np.random.normal(loc = arr, scale = abs(3e-5*arr))
return sample
def estimate_errors():
# number of Monte Carlo simulations.
N = 50
sample_space = np.arange(0, tmax, tmax / N)
# initialise array to store the oppo... | 0: 500.28 +- 0.15 days.
1: 1285.82 +- 0.31 days.
2: 2056.07 +- 0.44 days.
3: 2820.99 +- 0.58 days.
4: 3586.00 +- 0.76 days.
5: 4356.49 +- 1.04 days.
6: 5142.35 +- 1.60 days.
7: 5952.83 +- 2.08 days.
8: 6748.41 +- 1.76 days.
9: 7522.88 +- 1.65 days.
| MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 5Use historical positions of Earth and Mars (boundary value problem) to improve the accuracy of your prediction. What are the standard errors now?The `estimate_errors_improved` function should return two lists:1. a list (or array) of the mean opposition times for 10 oppositions2. a list (or array) of the standard... | def bc(ya, yb):
"""
:param ya: array of positions and velocities of Earth and Mars at t = -1000 days
:param yb: array of positions and velocities of Earth and Mars at t = 0 days
"""
# converting lists to arrays to have correct dimensions for solve_bvp.
ra = np.array(rspast)
ra = ra.reshape(6... | 0: 500.14 +- 0.09 days.
1: 1285.20 +- 0.18 days.
2: 2055.03 +- 0.25 days.
3: 2819.57 +- 0.33 days.
4: 3584.19 +- 0.44 days.
5: 4354.27 +- 0.60 days.
6: 5139.64 +- 0.91 days.
7: 5949.73 +- 1.20 days.
8: 6745.08 +- 1.00 days.
9: 7519.23 +- 0.94 days.
| MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Task 6Using the methods from Task 5, is there a better time point in the last 1000 days to get historical data for increasing the accuracy? Find such time t in the past 1000 days (-1000<$t$<0 days, where $t$=0 corresponds to 2 June 2019) which would yield a maximum error (std. deviation) of less than 0.2 days for eac... | # Remove the line that says "raise NotImplementedError"
# YOUR CODE HERE
raise NotImplementedError() | _____no_output_____ | MIT | c2/pde_solver.ipynb | c-abbott/num-rep |
Week 05, Part 1 Topic 1. For reference: about plotting polygons in R (we won't go over this, but it serves as reference) 1. Plotting normal distributions 1. Example: Manufacturing rulers 1. BACK TO SLIDES FOR PERCENTILES | # resize
require(repr)
options(repr.plot.width=8, repr.plot.height=8) | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
1. Intro to polygons in R Now we'll go over some useful functions associated with drawing normal distributions. First, a little intro of sequences and polygons: | x = seq(-3,3, length=10)
print(x) | [1] -3.0000000 -2.3333333 -1.6666667 -1.0000000 -0.3333333 0.3333333
[7] 1.0000000 1.6666667 2.3333333 3.0000000
| BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Now, lets try to understand a `polygon` function. We'll use this to help us draw areas using the `plot_polygons.R` script, but let's look at a few `polygon` examples.Let's make a triangle -- say the triangle goes from -3 to +3 in x & 0-1 in y: | plot(NULL,xlim=c(-3,3),ylim=c(0,1)) # sets up axes
xvertices = c(-3, 0, 3)
yvertices = c(0, 1, 0)
polygon(xvertices, yvertices,col="red") # plots on top of previous plot | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Let's try overplotting a little rectangle at x = (-1,1), y = (0.4,0.6): | # set up empty axis
plot(NULL,xlim=c(-3,3),ylim=c(0,1)) # sets up axes
# red triangle
xvertices = c(-3, 0, 3)
yvertices = c(0, 1, 0)
polygon(xvertices, yvertices,col="red") # plots on top of previous plot
# blue rectangle
xvertices = c(-1, -1, 1, 1)
yvertices = c(0.4, 0.6, 0.6, 0.4)
polygon(xvertices, yvertices, col=... | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Essentially, polygon just fills in between a list of verticies we give it. We can use this to plot underneath our normal distributions. This will help us get a "feel" for how much of the graph is related to our measurement of interest. 2. Plotting normal distributions Now, let's build some tool's we will need to exa... | help(dnorm)
x=seq(-3,3,length=200)
y=dnorm(x, mean=0, sd=1)
plot(x,y) | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Let's make a little fancier of a plot: | x = seq(-3,3,length=200) # plotting normal dist. -3,3 SD
y1 = dnorm(x, mean=0, sd=1)
plot(x,y1, type='l', ylim=c(0,2), ylab='Normal Distributions') | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Overplot a few other normal distributions: | # orig plot
x = seq(-3,3,length=200) # plotting normal dist. -3,3 SD
y1 = dnorm(x, mean=0, sd=1)
plot(x,y1, type='l', ylim=c(0,2), ylab='Normal Distributions')
# other distribution
y2 = dnorm(x, mean=0, sd=0.5)
par(new=TRUE) # for overplotting
plot(x, y2, type='l', col='red', ylim=c(0,2), ylab="") | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Let's add to this by visualizing a Z-score and actually calculating it as well. We'll go back to just one normal distribution.Z-scores: remember this is a measure of how "far off" a score is from the mean.So first, as is always a good example, let's plot! | x = seq(-6,6,length=200)
mean_dist = 1.0
sd_dist = 0.5 | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Note here: I'm calling the dnorm function directly in the "y" data position of this function this is instead of doing "y = dnorm..."Its just us being fancy :) | plot(x,dnorm(x,mean=mean_dist,sd=sd_dist),ylim=c(0,1.0), type='l') | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Let's say I want the Zscore for x=2.5 - i.e. given this normal distribution, if I measure pick out an observation that is at the value of 2.5, how off from the mean is it? First of course, lets plot! | plot(x,dnorm(x,mean=mean_dist,sd=sd_dist),ylim=c(0,1.0), type='l')
abline(v=2.5,col="red") | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
We can see already that its pretty far off from the mean here $\rightarrow$ if we by eye try to compare the area to the right of this line (the little tail) it is very small compared to the area to the left - so we expect our Z-score to be pretty big!Now let's actually calculate. Recall: $Z_{score} = \frac{observation... | Zscore = (2.5 - mean_dist)/sd_dist
print(Zscore) | [1] 3
| BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
This is saying our measurement of 2.5 is 3 times bigger than the standard deviation of our normal distribution. So pretty gosh-darn big! Now, let's say I've got a 2nd distribution with mean = 0.5 and sd=2, is the $Z_{score}$ at x=2.5 higher or lower than the first one?As always, let's start by plotting: | # old plot
plot(x,dnorm(x,mean=mean_dist,sd=sd_dist),ylim=c(0,1.0), type='l')
abline(v=2.5,col="red")
# 2nd distribution
mean_dist2 = 0.5
sd_dist2 = 2.0
par(new=TRUE) # overplot on our original axis
plot(x,dnorm(x,mean=mean_dist2,sd=sd_dist2),col="blue",ylim=c(0,1.0), type='l') | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
By eye we can see that the red line falls at a higher y-value on the blue, 2nd distribution this tells us at x=2.5, we are closer to the mean on the 2nd distribution so we expect a lower $Z_{score}$, but let's find out! | Zscore2 = (2.5-mean_dist2)/sd_dist2
print(Zscore2) | [1] 1
| BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Indeed 1 < 3 - in our 2nd distribution, an observation of x=2.5 is only 1 SD from the mean. $Z_{scores}$ allow us to in a sense "normalize" each normal distribution to allow for comparisions between normal distributiosn with different means & SDs. For example, if these distributions were measuring a test then a studen... | options(repr.plot.width=8, repr.plot.height=5) # nicer plotting window
#Plot: Run # 1: "mean of 11cm and an SD of 2.0cm"
x = seq(5,15,length=200)
plot(x,dnorm(x,mean=11,sd=2), type='l', ylim=c(0,0.2)) # further out for run #1
par(new=TRUE) # to overplot
#Plot: Run # 2: "mean of 10 cm and an SD of 4.0 cm"
plot(x,dnorm... | _____no_output_____ | BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
By eye, it looks like in run 1 (black) we are further from the mean (11cm), than for run 2 (blue). So this means that it is more unusual to get this 9cm ruler in run 1 than run2But let's do the calculation to be sure: | Z1 = (9.0-11)/2.0 # -1.0
Z2 = (9.0-10)/4.0 # -0.25
print(c("Run 1", "Run 2"))
print(c(Z1,Z2)) | [1] "Run 1" "Run 2"
[1] -1.00 -0.25
| BSD-3-Clause | week05/.ipynb_checkpoints/prep_notes_part1_week05_s2020_normalZscores-checkpoint.ipynb | jnaiman/is507_spring2021 |
Machine Learning with Linear Regression | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Data | customers = pd.read_csv('data/Ecommerce Customers')
customers.head()
customers.describe()
customers.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 500 entries, 0 to 499
Data columns (total 8 columns):
Email 500 non-null object
Address 500 non-null object
Avatar 500 non-null object
Avg. Session Length 500 non-null float64
Time on App 500 non-null fl... | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Exploratory Analysis | sns.jointplot(customers['Time on Website'],customers['Yearly Amount Spent'])
sns.jointplot(customers['Time on App'],customers['Yearly Amount Spent'])
sns.pairplot(customers)
customers.corr()
sns.lmplot('Length of Membership','Yearly Amount Spent',data=customers) | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Splitting the Data | customers.columns
#Selecting only the numerical features for training the model.
X = customers[['Avg. Session Length', 'Time on App','Time on Website', 'Length of Membership']]
y = customers['Yearly Amount Spent']
from sklearn.model_selection import train_test_split
X_test,X_train,y_test,y_train = train_test_split(X,y,... | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Training the Model | from sklearn.linear_model import LinearRegression
lm = LinearRegression()
lm.fit(X_train,y_train) | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Making Predictions | predictions = lm.predict(X_test)
plt.scatter(y_test,predictions) | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Evaluation and Understanding Results | from sklearn import metrics
print('MAE:',metrics.mean_absolute_error(y_test,predictions))
print('MSE:',metrics.mean_squared_error(y_test,predictions))
print('RMSE:',np.sqrt(metrics.mean_squared_error(y_test,predictions)))
cust_coeff = pd.DataFrame(lm.coef_,X.columns)
cust_coeff.columns = ['Coefficient']
cust_coeff | _____no_output_____ | MIT | ML Micro Projects/Machine Learning with Linear Regression.ipynb | anaxsouza/Data_Science_and_ML_Portfolio |
Introduction on Using Python to access GeoNet's GNSS data In this notebook we will learn how to get data from one GNSS(Global Navigation Satellite System) station. By the end of this tutorial you will have make a graph like the one below. Table of contents 1. Introduction 2. Building the base FITS query 3. Get... | import requests
import pandas as pd
import datetime
import matplotlib.pyplot as plt
pd.plotting.register_matplotlib_converters() | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Set URL and endpoint | base_url = "http://fits.geonet.org.nz/"
endpoint = "observation" | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The base URL should be set as above to access the FITS database webservice containing the GeoNet GNSS data. The endpoint is set to observation to get the data itself in csv format. There are other endpoints which will return different information such as plot and site. To learn more go to https://fits.geonet.org.nz/api... | url = base_url + endpoint | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Combine the base URL and the endpoint to give the information to request the data. 3. Get GNSS data In this section we will learn how to get all the GNSS observation data from a site and put it into a pandas dataframe, so we can plot and save the data Set query parameters | parameters ={"typeID": "e", "siteID": "HANM"} | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Set the parameters to get the east component(`'typeID':'e'`) of the GNSS station in the Hanmer Basin (`'siteID': 'HANM'`). To find the 4 letter site ID of a station you can use https://www.geonet.org.nz/data/network/sensor/search to find stations in an area of interest Get GNSS data | response_e = requests.get(url, params=parameters) | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
We use `requests.get` to get the data using the URL we made earlier and the parameters we set in the last stage | parameters["typeID"] = "n"
response_n = requests.get(url, params=parameters)
parameters["typeID"] = "u"
response_u = requests.get(url, params=parameters) | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Here we've changed the typeID in the parameters dictionary to get the other components for the GNSS station Check that your requests worked | print ("The Response status code of the east channel is", response_e.status_code)
print ("The Response status code of the north channel is",response_n.status_code)
print ("The Response status code of the up channel is",response_u.status_code) | The Response status code of the east channel is 200
The Response status code of the north channel is 200
The Response status code of the up channel is 200
| Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The response status code says whether we were successful in getting the data requested and why not if we were unsuccessful:200 -- everything went okay, and the result has been returned (if any)301 -- the server is redirecting you to a different endpoint. This can happen when a company switches domain names, or an endpo... | data_e = response_e.content.decode("utf-8").split("\n") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The above code decodes the response and then splits the east displacement data on the new line symbol as each line is one point of data. If you are using Python2 remove the code `.decode("utf-8")` Split the points of data | for i in range(0, len(data_e)):
data_e[i]= data_e[i].split(",") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The above code uses a for loop to split each point of data on the "," symbol as each value is separated by a ",", producing a list of lists Reformat data values | for i in range(1, (len(data_e)-1)):
data_e[i][0] = datetime.datetime.strptime(data_e[i][0], '%Y-%m-%dT%H:%M:%S.%fZ') #make 1st value into a datetime object
data_e[i][1] = float(data_e[i][1]) #makes 2nd value into a decimal number
data_e[i][2] = float(data_e[i][2]) #makes 3rd value into a decimal number | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The above code uses a `for` loop to go over each point of data and reformat it, so that the first value in each point is seen as a time, and the second and third values are seen as numbers.Note that we choose to miss the first and last data points in our loop as the first data point has the names of the data values and... | df_e = pd.DataFrame(data_e[1:-1],index = range(1, (len(data_e)-1)), columns=data_e[0]) | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
`data_e[1:-1]` makes the list of data be the data in the data frame, `index = range(1, (len(data_e)-1))` makes rows named 1, 2, ... n where n is the number of data points, and `columns=data_e[0]` gives the columns the names that where in the first line of the response string Print the first few lines of the data fram... | df_e.head() | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Here we can see on the 4th of June 2014 how much the site HANM had moved east (with formal error) in mm from its reference position, this being the midpoint of the position timeseries. Make everything we have just done into a function | def GNSS_dataframe(data):
"""
This function turns the string of GNSS data received by requests.get
into a data frame with GNSS data correctly formatted.
"""
data = data.split("\n") # splits data on the new line symbol
for i in range(0, len(data)):
data[i]= data[i].split(",")# splits data... | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
This makes code cells 8 to 11 into a function to be called later in the notebook. Run the above function on the North and Up data | df_n = GNSS_dataframe(response_n.content.decode("utf-8"))
df_u = GNSS_dataframe(response_u.content.decode("utf-8")) | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Make sure to run this function on the content string of the requested data. If in Python2 use remove the code `.decode("utf-8")` Why make the data into a data frame? A data frame is a way of formatting data into a table with column and row name much like a csv file and makes long list of data a lot easier to use. Dat... | e_plot = df_e.plot(x='date-time', y= ' e (mm)', marker='o', title = 'Relative east displacement for HANM')
#plt.savefig("e_plot") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The above code plots time on the x axis and the displacement in millimetres on the y axis. `marker = ‘o’` makes each point of data a small circle. If you want to save the plot as a png file in the folder you are running this code from you can uncomment ` plt.savefig("e_plot")` Plot the north data | n_plot = df_n.plot(x='date-time', y= ' n (mm)', marker='o', title = 'Relative north displacement for HANM')
#plt.savefig("n_plot") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Plot the up data | u_plot = df_u.plot(x='date-time', y= ' u (mm)', marker='o', title='Relative up displacement for HANM')
#plt.savefig("u_plot") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
5. Save data Make a copy of the east data frame | df = df_e | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
This makes what is call a deep copy of the data frame with the east displacement data in it. This means that if `df` is edited `df_e` is not effected. Remove the error column from this copy of the data | df = df.drop(" error (mm)",axis=1) | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
The above code removes the column called error (mm) and all its data from `df`. ` axis=1` says that we are looking for a column. If we put ` axis=0` we would be looking for a row. Add the up and north data to this data frame (but not the respective errors) | df["u (mm)"] = df_u[' u (mm)']
df["n (mm)"] = df_n[' n (mm)'] | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Print the first few lines of the data frame | df.head() | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Here we can see the layout of the data frame with the columns date, east displacement, up displacement and north displacement Save as CSV file | df.to_csv("HANM.csv") | _____no_output_____ | Apache-2.0 | GNSS_Data/Python/Introduction_to_GNSS_data_using_FITS_in_Python.ipynb | megankortink/data-tutorials |
Preprocessing the input data | # concat last name and first name
sdf['name_last_name_first'] = sdf['name_last'] + ' ' + sdf['name_first']
# build n-gram list
vect = CountVectorizer(analyzer='char', max_df=0.3, min_df=3, ngram_range=(NGRAMS, NGRAMS), lowercase=False)
a = vect.fit_transform(sdf.name_last_name_first)
vocab = vect.vocabulary_
# sort ... | num_words = 1260
Max feature len = 41, Avg. feature len = 12
| MIT | ethnicolr/models/ethnicolr_keras_lstm_fl_voter_name.ipynb | djakaitis/ethnicolr |
Train a LSTM modelref: http://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/ | '''The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF + LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
choice of loss and optimizer is critical, etc.
Some configurations won't converge.
- LSTM loss decrease patterns during tr... | Test score: 0.45394647121429443
Test accuracy: 0.8408349752426147
| MIT | ethnicolr/models/ethnicolr_keras_lstm_fl_voter_name.ipynb | djakaitis/ethnicolr |
Confusion Matrix | p = model.predict(X_test, verbose=2) # to predict probability
y_pred = np.argmax(p, axis=-1)
target_names = list(sdf.race.astype('category').cat.categories)
print(classification_report(np.argmax(y_test, axis=1), y_pred, target_names=target_names))
print(confusion_matrix(np.argmax(y_test, axis=1), y_pred)) | 6250/6250 - 32s
precision recall f1-score support
asian 0.81 0.42 0.55 3876
hispanic 0.82 0.86 0.84 33455
nh_black 0.76 0.43 0.55 28290
nh_white 0.86 0.93 0.89 134379
accuracy ... | MIT | ethnicolr/models/ethnicolr_keras_lstm_fl_voter_name.ipynb | djakaitis/ethnicolr |
Save model | model.save('./fl_voter_reg/lstm/fl_all_name_lstm.h5')
words_df = pd.DataFrame(words_list, columns=['vocab'])
words_df.to_csv('./fl_voter_reg/lstm/fl_all_name_vocab.csv', index=False, encoding='utf-8')
| _____no_output_____ | MIT | ethnicolr/models/ethnicolr_keras_lstm_fl_voter_name.ipynb | djakaitis/ethnicolr |
Principal Componenet Analysis (PCA)The PCA algorithm is a dimensionality reduction algorithm which works really well for datasets which have correlated columns. It combines the features of X in linear combination such that the new components capture the most information of the data. The PCA model is implemented in the... | import numpy as np
import pandas as pd
from sklearn.decomposition import PCA as skPCA
from cuml import PCA as cumlPCA
import cudf
import os | _____no_output_____ | Apache-2.0 | cuml/pca_demo.ipynb | divyegala/notebooks |
Helper Functions | # calculate the time required by a cell to run
from timeit import default_timer
class Timer(object):
def __init__(self):
self._timer = default_timer
def __enter__(self):
self.start()
return self
def __exit__(self, *args):
self.stop()
def start(self):
"""St... | _____no_output_____ | Apache-2.0 | cuml/pca_demo.ipynb | divyegala/notebooks |
Run tests | %%time
# nrows = number of samples
# ncols = number of features of each sample
nrows = 2**15
nrows = int(nrows * 1.5)
ncols = 400
X = load_data(nrows,ncols)
print('data',X.shape)
# set parameters for the PCA model
n_components = 10
whiten = False
random_state = 42
svd_solver="full"
%%time
# use the sklearn PCA on the... | compare pca: cuml vs sklearn transformed results equal
| Apache-2.0 | cuml/pca_demo.ipynb | divyegala/notebooks |
Deploy and perform inference on Model Package from AWS Marketplace This notebook provides you instructions on how to deploy and perform inference on model packages from AWS Marketplace object detection model.This notebook is compatible only with those object detection model packages which this notebook is linked to. P... | model_package_arn='<Customer to specify Model package ARN corresponding to their AWS region>'
import json
from sagemaker import ModelPackage
import sagemaker as sage
from sagemaker import get_execution_role
import matplotlib.patches as patches
import numpy as np
from matplotlib import pyplot as plt
from PIL import Im... | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
In next step, you would be deploying the model for real-time inference. For information on how real-time inference with Amazon SageMaker works, see [Documentation](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-hosting.html). 2. Create an endpoint and perform real-time inference | model_name='object-detection-model'
#The object detection model packages this notebook notebook is compatible with, support application/x-image as the
#content-type.
content_type='application/x-image' | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
Review and update the compatible instance type for the model package in the following cell. | real_time_inference_instance_type='ml.g4dn.xlarge'
batch_transform_inference_instance_type='ml.p2.xlarge' | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
A. Create an endpoint | #create a deployable model from the model package.
model = ModelPackage(role=role,
model_package_arn=model_package_arn,
sagemaker_session=sagemaker_session)
#Deploy the model
predictor = model.deploy(1, real_time_inference_instance_type, endpoint_name=model_name) | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
Once endpoint has been created, you would be able to perform real-time inference. B. Prepare input file for performing real-time inferenceIn this step, we will download class_id_to_label_mapping from S3 bucket. The mapping files has been downloaded from [TensorFlow](https://storage.googleapis.com/download.tensorflow.o... | s3_bucket = f"jumpstart-cache-prod-{region}"
key_prefix = "inference-notebook-assets"
def download_from_s3(key_filenames):
for key_filename in key_filenames:
s3.download_file(s3_bucket, f"{key_prefix}/{key_filename}", key_filename)
img_jpg = "Naxos_Taverna.jpg"
#Download image
download_from_s3(key_filena... | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
C. Query endpoint that you have created with the opened images | #perform_inference method performs inference on the endpoint and prints predictions.
def perform_inference(filename):
response = runtime.invoke_endpoint(EndpointName='test-tensorflow-test', ContentType=content_type, Body=input_img)
model_predictions = json.loads(response['Body'].read())
return model_predict... | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
D. Display model predictions as bounding boxes on the input image | colors = list(ImageColor.colormap.values())
image_pil = Image.open(img_jpg)
image_np = np.array(image_pil)
plt.figure(figsize=(20,20))
ax = plt.axes()
ax.imshow(image_np)
classes = [class_id_to_label[str(int(index))] for index in result["detection_classes"][0]]
bboxes, confidences = result["detection_boxes"][0], resu... | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
D. Delete the endpoint Now that you have successfully performed a real-time inference, you do not need the endpoint any more. You can terminate the endpoint to avoid being charged. | model.sagemaker_session.delete_endpoint(model_name)
model.sagemaker_session.delete_endpoint_config(model_name) | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
3. Perform batch inference In this section, you will perform batch inference using multiple input payloads together. If you are not familiar with batch transform, and want to learn more, see [How to run a batch transform job](https://docs.aws.amazon.com/sagemaker/latest/dg/how-it-works-batch.html) | #upload the batch-transform job input files to S3
transform_input_key_prefix = 'object-detection-model-transform-input'
transform_input = sagemaker_session.upload_data(img_jpg, key_prefix=transform_input_key_prefix)
print("Transform input uploaded to " + transform_input)
#Run the batch-transform job
transformer = mode... | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
4. Clean-up A. Delete the model | model.delete_model() | _____no_output_____ | MIT-0 | using_open_source_model_packages/tensorflow_od_model/using_object_detection_model.ipynb | Leggerla/aws-marketplace-machine-learning |
PDF da apresentação:
https://drive.google.com/file/d/1k5xfHrWnjPJJc05kB3op_05PAZpZpAfO/view
| def ma(lista):
soma = 0
cont = 0
for i in lista:
soma = soma + i
cont = cont + 1
return soma/cont
def mg(lista):
prod = 1
cont = 0
for i in lista:
prod = prod*i
cont = cont + 1
return prod**(1/cont)
def mediaAG(lista, tip = 0):
if (tip == 0):
r = ma(lista)
el... | A média aritmética é: 8.00
A média geométrica é: 7.96
| MIT | Módulo07Aula24.ipynb | julianovale/pythonparatodos |
TimeseriesCe notebook présente quelques étapes simples pour une série temporelle. La plupart utilise le module [statsmodels.tsa](https://www.statsmodels.org/stable/tsa.htmlmodule-statsmodels.tsa). | from jyquickhelper import add_notebook_menu
add_notebook_menu()
%matplotlib inline | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
DonnéesLes données sont artificielles mais simulent ce que pourraient être le chiffre d'affaires d'un magasin de quartier, des samedi très forts, une semaine morne, un Noël chargé, un été plat. | from ensae_teaching_cs.data import generate_sells
import pandas
df = pandas.DataFrame(generate_sells())
df.head() | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Premiers graphiquesLa série a deux saisonnalités, hebdomadaire, mensuelle. | import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 2, figsize=(14, 4))
df.iloc[-30:].set_index('date').plot(ax=ax[0])
df.set_index('date').plot(ax=ax[1])
ax[0].set_title("chiffre d'affaire sur le dernier mois")
ax[1].set_title("chiffre d'affaire sur deux ans"); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Elle a une vague tendance, on peut calculer un tendance à l'ordre 1, 2, ... | from statsmodels.tsa.tsatools import detrend
notrend = detrend(df.value, order=1)
df["notrend"] = notrend
df["trend"] = df['value'] - notrend
ax = df.plot(x="date", y=["value", "trend"], figsize=(14,4))
ax.set_title('tendance'); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Autocorrélations... | from statsmodels.tsa.stattools import acf
cor = acf(df.value)
cor
fig, ax = plt.subplots(1, 1, figsize=(14,2))
ax.plot(cor)
ax.set_title("Autocorrélogramme"); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
La première saisonalité apparaît, 7, 14, 21... Les autocorrélations partielles confirment cela, plutôt 7 jours. | from statsmodels.tsa.stattools import pacf
from statsmodels.graphics.tsaplots import plot_pacf
plot_pacf(df.value, lags=50); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Comme il n'y a rien le dimanche, il vaut mieux les enlever. Garder des zéros nous priverait de modèles multiplicatifs. | df["weekday"] = df.date.dt.weekday
df.head()
df_nosunday = df[df.weekday != 6]
df_nosunday.head(n=10)
fig, ax = plt.subplots(1, 1, figsize=(14,2))
cor = acf(df_nosunday.value)
ax.plot(cor)
ax.set_title("Autocorrélogramme");
plot_pacf(df_nosunday.value, lags=50); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
On décompose la série en tendance + saisonnalité. Les étés et Noël apparaissent. | from statsmodels.tsa.seasonal import seasonal_decompose
res = seasonal_decompose(df_nosunday.value, freq=7)
res.plot();
plt.plot(res.seasonal[-30:])
plt.title("Saisonnalité");
cor = acf(res.trend[5:-5]);
plt.plot(cor); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
On cherche maintenant la saisonnalité de la série débarrassée de sa tendance herbdomadaire. On retrouve la saisonnalité mensuelle. | res_year = seasonal_decompose(res.trend[5:-5], freq=25)
res_year.plot(); | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Test de stationnaritéLe test [KPSS](https://en.wikipedia.org/wiki/KPSS_test) permet de tester la stationnarité d'une série. | from statsmodels.tsa.stattools import kpss
kpss(res.trend[5:-5]) | c:\python372_x64\lib\site-packages\statsmodels\tsa\stattools.py:1276: InterpolationWarning: p-value is smaller than the indicated p-value
warn("p-value is smaller than the indicated p-value", InterpolationWarning)
| MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Comme ce n'est pas toujours facile à interpréter, on simule une variable aléatoire gaussienne donc sans tendance. | from numpy.random import randn
bruit = randn(1000)
kpss(bruit) | c:\python372_x64\lib\site-packages\statsmodels\tsa\stattools.py:1278: InterpolationWarning: p-value is greater than the indicated p-value
warn("p-value is greater than the indicated p-value", InterpolationWarning)
| MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Et puis une série avec une tendance forte. | from numpy.random import randn
from numpy import arange
bruit = randn(1000) * 100 + arange(1000) / 10
kpss(bruit) | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Une valeur forte indique une tendance et la série en a clairement une. PrédictionLes modèles *AR*, *ARMA*, *ARIMA* se concentrent sur une série à une dimension. En machine learning, il y a la série et plein d'autres informations. On construit une matrice avec des séries décalées. | from statsmodels.tsa.tsatools import lagmat
lag = 8
X = lagmat(df_nosunday["value"], lag)
lagged = df_nosunday.copy()
for c in range(1,lag+1):
lagged["lag%d" % c] = X[:, c-1]
lagged.tail() | _____no_output_____ | MIT | _doc/notebooks/td2a_ml/seasonal_timeseries.ipynb | Jerome-maker/ensae_teaching_cs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.