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 |
|---|---|---|---|---|---|
Data Scaling Standardize a dataset along any axis.Center to the mean and component wise scale to unit variance.For more information... [click here](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html) |
x_train = preprocessing.scale(x_train)
x_test = preprocessing.scale(x_test) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
ModelLassoLars is a lasso model implemented using the LARS algorithm, and unlike the implementation based on coordinate descent, this yields the exact solution, which is piecewise linear as a function of the norm of its coefficients. Tuning parameters> **fit_intercept** -> whether to calculate the intercept for this m... | model=LassoLars()
model.fit(x_train,y_train) | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Model AccuracyWe will use the trained model to make a prediction on the test set.Then use the predicted value for measuring the accuracy of our model.score: The score function returns the coefficient of determination R2 of the prediction. | print("Accuracy score {:.2f} %\n".format(model.score(x_test,y_test)*100)) | Accuracy score 79.47 %
| Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
> **r2_score**: The **r2_score** function computes the percentage variablility explained by our model, either the fraction or the count of correct predictions. > **mae**: The **mean abosolute error** function calculates the amount of total error(absolute average distance between the real data and the predicted data) b... | y_pred=model.predict(x_test)
print("R2 Score: {:.2f} %".format(r2_score(y_test,y_pred)*100))
print("Mean Absolute Error {:.2f}".format(mean_absolute_error(y_test,y_pred)))
print("Mean Squared Error {:.2f}".format(mean_squared_error(y_test,y_pred))) | R2 Score: 79.47 %
Mean Absolute Error 3923.32
Mean Squared Error 31383167.17
| Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
Prediction PlotFirst, we make use of a plot to plot the actual observations, with x_train on the x-axis and y_train on the y-axis.For the regression line, we will use x_train on the x-axis and then the predictions of the x_train observations on the y-axis. | plt.figure(figsize=(14,10))
plt.plot(range(20),y_test[0:20], color = "green")
plt.plot(range(20),model.predict(x_test[0:20]), color = "red")
plt.legend(["Actual","prediction"])
plt.title("Predicted vs True Value")
plt.xlabel("Record number")
plt.ylabel(target)
plt.show() | _____no_output_____ | Apache-2.0 | Regression/Linear Models/LassoLars_Scale.ipynb | surya2365/ds-seed |
[Table of Contents](./table_of_contents.ipynb) Discrete Bayes Filter 离散贝叶斯滤波 | %matplotlib inline
#format the book
import book_format
book_format.set_style() | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
The Kalman filter belongs to a family of filters called *Bayesian filters*. Most textbook treatments of the Kalman filter present the Bayesian formula, perhaps shows how it factors into the Kalman filter equations, but mostly keeps the discussion at a very abstract level. That approach requires a fairly sophisticated u... | import numpy as np
belief = np.array([1/10]*10)
print(belief) | [0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]
| CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
In [Bayesian statistics](https://en.wikipedia.org/wiki/Bayesian_probability) this is called a [*prior*](https://en.wikipedia.org/wiki/Prior_probability). It is the probability prior to incorporating measurements or other information. More completely, this is called the *prior probability distribution*. A [*probability ... | hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0]) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
I start listening to Simon's transmissions on the network, and the first data I get from the sensor is **door**. For the moment assume the sensor always returns the correct answer. From this I conclude that he is in front of a door, but which one? I have no reason to believe he is in front of the first, second, or thir... | import kf_book.book_plots as book_plots
from kf_book.book_plots import figsize, set_figsize
import matplotlib.pyplot as plt
belief = np.array([1/3, 1/3, 0, 0, 0, 0, 0, 0, 1/3, 0])
book_plots.bar_plot(belief) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This distribution is called a [*categorical distribution*](https://en.wikipedia.org/wiki/Categorical_distribution), which is a discrete distribution describing the probability of observing $n$ outcomes. It is a [*multimodal distribution*](https://en.wikipedia.org/wiki/Multimodal_distribution) because we have multiple b... | belief = hallway * (1/3)
print(belief) | [0.333 0.333 0. 0. 0. 0. 0. 0. 0.333 0. ]
| CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Extracting Information from Sensor ReadingsLet's put Python aside and think about the problem a bit. Suppose we were to read the following from Simon's sensor: * door * move right * door Can we deduce Simon's location? Of course! Given the hallway's layout there is only one place from which you can get this sequen... | belief = np.array([0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
I designed the hallway layout and sensor readings to give us an exact answer quickly. Real problems are not so clear cut. But this should trigger your intuition - the first sensor reading only gave us low probabilities (0.333) for Simon's location, but after a position update and another sensor reading we know more abo... | def update_belief(hall, belief, z, correct_scale):
for i, val in enumerate(hall):
if val == z:
belief[i] *= correct_scale
belief = np.array([0.1] * 10)
reading = 1 # 1 is 'door'
update_belief(hallway, belief, z=reading, correct_scale=3.)
print('belief:', belief)
print('sum =', sum(belief))
plt.... | belief: [0.3 0.3 0.1 0.1 0.1 0.1 0.1 0.1 0.3 0.1]
sum = 1.6000000000000003
| CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This is not a probability distribution because it does not sum to 1.0. But the code is doing mostly the right thing - the doors are assigned a number (0.3) that is 3 times higher than the walls (0.1). All we need to do is normalize the result so that the probabilities correctly sum to 1.0. Normalization is done by divi... | belief / sum(belief) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
FilterPy implements this with the `normalize` function:```Pythonfrom filterpy.discrete_bayes import normalizenormalize(belief)```It is a bit odd to say "3 times as likely to be right as wrong". We are working in probabilities, so let's specify the probability of the sensor being correct, and compute the scale factor fr... | hallway == 1 | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
When you use the boolean array as an index to another array it returns only the elements where the index is `True`. Thus we can replace the `for` loop with```pythonbelief[hall==z] *= scale```and only the elements which equal `z` will be multiplied by `scale`.Teaching you NumPy is beyond the scope of this book. I will u... | from filterpy.discrete_bayes import normalize
def scaled_update(hall, belief, z, z_prob):
scale = z_prob / (1. - z_prob)
belief[hall==z] *= scale
normalize(belief)
belief = np.array([0.1] * 10)
scaled_update(hallway, belief, z=1, z_prob=.75)
print('sum =', sum(belief))
print('probability of door =', bel... | sum = 1.0
probability of door = 0.1875
probability of wall = 0.06249999999999999
| CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
We can see from the output that the sum is now 1.0, and that the probability of a door vs wall is still three times larger. The result also fits our intuition that the probability of a door must be less than 0.333, and that the probability of a wall must be greater than 0.0. Finally, it should fit our intuition that w... | def scaled_update(hall, belief, z, z_prob):
scale = z_prob / (1. - z_prob)
likelihood = np.ones(len(hall))
likelihood[hall==z] *= scale
return normalize(likelihood * belief) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This function is not fully general. It contains knowledge about the hallway, and how we match measurements to it. We always strive to write general functions. Here we will remove the computation of the likelihood from the function, and require the caller to compute the likelihood themselves.Here is a full implementatio... | from filterpy.discrete_bayes import update
def lh_hallway(hall, z, z_prob):
""" compute likelihood that a measurement matches
positions in the hallway."""
try:
scale = z_prob / (1. - z_prob)
except ZeroDivisionError:
scale = 1e8
likelihood = np.ones(len(hall))
likelihood[h... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Incorporating MovementRecall how quickly we were able to find an exact solution when we incorporated a series of measurements and movement updates. However, that occurred in a fictional world of perfect sensors. Might we be able to find an exact solution with noisy sensors?Unfortunately, the answer is no. Even if the ... | def perfect_predict(belief, move):
""" move the position by `move` spaces, where positive is
to the right, and negative is to the left
"""
n = len(belief)
result = np.zeros(n)
for i in range(n):
result[i] = belief[(i-move) % n]
return result
belief = np.array([.35, .1, .2, ... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
We can see that we correctly shifted all values one position to the right, wrapping from the end of the array back to the beginning. The next cell animates this so you can see it in action. Use the slider to move forwards and backwards in time. This simulates Simon walking around and around the hallway. It does not yet... | from ipywidgets import interact, IntSlider
belief = np.array([.35, .1, .2, .3, 0, 0, 0, 0, 0, .05])
perfect_beliefs = []
for _ in range(20):
# Simon takes one step to the right
belief = perfect_predict(belief, 1)
perfect_beliefs.append(belief)
def simulate(time_step):
book_plots.bar_plot(perfect_beli... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
TerminologyLet's pause a moment to review terminology. I introduced this terminology in the last chapter, but let's take a second to help solidify your knowledge. The *system* is what we are trying to model or filter. Here the system is our dog. The *state* is its current configuration or value. In this chapter the st... | def predict_move(belief, move, p_under, p_correct, p_over):
n = len(belief)
prior = np.zeros(n)
for i in range(n):
prior[i] = (
belief[(i-move) % n] * p_correct +
belief[(i-move-1) % n] * p_over +
belief[(i-move+1) % n] * p_under)
return prior
belief ... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
It appears to work correctly. Now what happens when our belief is not 100% certain? 看起來代碼工作正常。現在我們看看置信度不是100%的情況會是怎樣? | belief = [0, 0, .4, .6, 0, 0, 0, 0, 0, 0]
prior = predict_move(belief, 2, .1, .8, .1)
book_plots.plot_belief_vs_prior(belief, prior)
prior | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Here the results are more complicated, but you should still be able to work it out in your head. The 0.04 is due to the possibility that the 0.4 belief undershot by 1. The 0.38 is due to the following: the 80% chance that we moved 2 positions (0.4 $\times$ 0.8) and the 10% chance that we undershot (0.6 $\times$ 0.1). O... | belief = np.array([1.0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
predict_beliefs = []
for i in range(100):
belief = predict_move(belief, 1, .1, .8, .1)
predict_beliefs.append(belief)
print('Final Belief:', belief)
# make interactive plot
def show_prior(step):
book_plots.bar_plot(predict_beliefs[step-1])
plt.t... | Final Belief: [0.104 0.103 0.101 0.099 0.097 0.096 0.097 0.099 0.101 0.103]
| CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
After 100 iterations we have lost almost all information, even though we were 100% sure that we started in position 0. Feel free to play with the numbers to see the effect of differing number of updates. For example, after 100 updates a small amount of information is left, after 50 a lot is left, but by 200 iterations ... | def predict_move_convolution(pdf, offset, kernel):
N = len(pdf)
kN = len(kernel)
width = int((kN - 1) / 2)
prior = np.zeros(N)
for i in range(N):
for k in range (kN):
index = (i + (width-k) - offset) % N
prior[i] += pdf[index] * kernel[k]
return prior | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This illustrates the algorithm, but it runs very slow. SciPy provides a convolution routine `convolve()` in the `ndimage.filters` module. We need to shift the pdf by `offset` before convolution; `np.roll()` does that. The move and predict algorithm can be implemented with one line:```pythonconvolve(np.roll(pdf, offset... | from filterpy.discrete_bayes import predict
belief = [.05, .05, .05, .05, .55, .05, .05, .05, .05, .05]
prior = predict(belief, offset=1, kernel=[.1, .8, .1])
book_plots.plot_belief_vs_prior(belief, prior, ylim=(0,0.6)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
All of the elements are unchanged except the middle ones. The values in position 4 and 6 should be $$(0.1 \times 0.05)+ (0.8 \times 0.05) + (0.1 \times 0.55) = 0.1$$Position 5 should be $$(0.1 \times 0.05) + (0.8 \times 0.55)+ (0.1 \times 0.05) = 0.45$$Let's ensure that it shifts the positions correctly for movements g... | prior = predict(belief, offset=3, kernel=[.05, .05, .6, .2, .1])
book_plots.plot_belief_vs_prior(belief, prior, ylim=(0,0.6)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
The position was correctly shifted by 3 positions and we give more weight to the likelihood of an overshoot vs an undershoot, so this looks correct.Make sure you understand what we are doing. We are making a prediction of where the dog is moving, and convolving the probabilities to get the prior.If we weren't using pro... | from filterpy.discrete_bayes import update
hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])
prior = np.array([.1] * 10)
likelihood = lh_hallway(hallway, z=1, z_prob=.75)
posterior = update(likelihood, prior)
book_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
After the first update we have assigned a high probability to each door position, and a low probability to each wall position. 第一次更新後,我们为每个门的位置分配了更高的权重,而为墙壁的位置赋予了较低的权重。 | kernel = (.1, .8, .1)
prior = predict(posterior, 1, kernel)
book_plots.plot_prior_vs_posterior(prior, posterior, True, ylim=(0,.5)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
The predict step shifted these probabilities to the right, smearing them about a bit. Now let's look at what happens at the next sense. 预测操作使得概率分布右移,并且使分布散得更开。现在让我们看看下一个读入传感器的读数会发生什么。 | likelihood = lh_hallway(hallway, z=1, z_prob=.75)
posterior = update(likelihood, prior)
book_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Notice the tall bar at position 1. This corresponds with the (correct) case of starting at position 0, sensing a door, shifting 1 to the right, and sensing another door. No other positions make this set of observations as likely. Now we will add an update and then sense the wall. 注意看位置1处的高峰。它对应的(正確)情況是:以位置0为起点出發,傳感器感應到... | prior = predict(posterior, 1, kernel)
likelihood = lh_hallway(hallway, z=0, z_prob=.75)
posterior = update(likelihood, prior)
book_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This is exciting! We have a very prominent bar at position 2 with a value of around 35%. It is over twice the value of any other bar in the plot, and is about 4% larger than our last plot, where the tallest bar was around 31%. Let's see one more cycle. 結果真是令人激動!條形圖在位置2處的數值顯著突出,其值為35%,其高度在其它任意一柱高度的兩倍以上。上一張圖的最高高度約為31%,所以... | prior = predict(posterior, 1, kernel)
likelihood = lh_hallway(hallway, z=0, z_prob=.75)
posterior = update(likelihood, prior)
book_plots.plot_prior_vs_posterior(prior, posterior, ylim=(0,.5)) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
I ignored an important issue. Earlier I assumed that we had a motion sensor for the predict step; then, when talking about the dog and the microwave I assumed that you had no knowledge that he suddenly began running. I mentioned that your belief that the dog is running would increase over time, but I did not provide an... | book_plots.predict_update_chart() | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
This filter is a form of the g-h filter. Here we are using the percentages for the errors to implicitly compute the $g$ and $h$ parameters. We could express the discrete Bayes algorithm as a g-h filter, but that would obscure the logic of this filter.The filter equations are:$$\begin{aligned} \bar {\mathbf x} &= \mathb... | def discrete_bayes_sim(prior, kernel, measurements, z_prob, hallway):
posterior = np.array([.1]*10)
priors, posteriors = [], []
for i, z in enumerate(measurements):
prior = predict(posterior, 1, kernel)
priors.append(prior)
likelihood = lh_hallway(hallway, z, z_prob)
posteri... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Let's run the filter and animate it. 讓我們運行濾波器,並觀察運行結果。 | # change these numbers to alter the simulation
kernel = (.1, .8, .1)
z_prob = 1.0
hallway = np.array([1, 1, 0, 0, 0, 0, 0, 0, 1, 0])
# measurements with no noise
zs = [hallway[i % len(hallway)] for i in range(50)]
priors, posteriors = discrete_bayes_sim(prior, kernel, zs, z_prob, hallway)
interact(animate_discrete_ba... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Now we can see the results. You can see how the prior shifts the position and reduces certainty, and the posterior stays in the same position and increases certainty as it incorporates the information from the measurement. I've made the measurement perfect with the line `z_prob = 1.0`; we will explore the effect of imp... | hallway = np.array([1, 0, 1, 0, 0]*2)
kernel = (.1, .8, .1)
prior = np.array([.1] * 10)
zs = [1, 0, 1, 0, 0, 1]
z_prob = 0.75
priors, posteriors = discrete_bayes_sim(prior, kernel, zs, z_prob, hallway)
interact(animate_discrete_bayes(hallway, priors, posteriors), step=IntSlider(value=12, max=len(zs)*2)); | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
We have identified the likely cases of having started at position 0 or 5, because we saw this sequence of doors and walls: 1,0,1,0,0. Now I inject a bad measurement. The next measurement should be 0, but instead we get a 1: 我們看到最可能的起始位置是0或5。這是因為傳感器的讀數序列為:1、0、1、0、0.現在我插入一個錯誤的測量值。原本下一個讀數應當是0,但我將其替換為1. | measurements = [1, 0, 1, 0, 0, 1, 1]
priors, posteriors = discrete_bayes_sim(prior, kernel, measurements, z_prob, hallway);
plot_posterior(hallway, posteriors, 6) | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
That one bad measurement has significantly eroded our knowledge. Now let's continue with a series of correct measurements. 一個不良傳感器數據的插入嚴重污染了我們的知識。接著,我們在正確測量數據上繼續運行。 | with figsize(y=5.5):
measurements = [1, 0, 1, 0, 0, 1, 1, 1, 0, 0]
for i, m in enumerate(measurements):
likelihood = lh_hallway(hallway, z=m, z_prob=.75)
posterior = update(likelihood, prior)
prior = predict(posterior, 1, kernel)
plt.subplot(5, 2, i+1)
book_plots.bar_plot... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
We quickly filtered out the bad sensor reading and converged on the most likely positions for our dog. 我們很快就濾除了不良傳感器讀數,並且概率分佈收斂在狗的最可能位置上。 Drawbacks and LimitationsDo not be mislead by the simplicity of the examples I chose. This is a robust and complete filter, and you may use the code in real world solutions. If you ... | class Train(object):
def __init__(self, track_len, kernel=[1.], sensor_accuracy=.9):
self.track_len = track_len
self.pos = 0
self.kernel = kernel
self.sensor_accuracy = sensor_accuracy
def move(self, distance=1):
""" move in the specified direction
with some sma... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
With that we are ready to write the filter. We will put it in a function so that we can run it with different assumptions. I will assume that the robot always starts at the beginning of the track. The track is implemented as being 10 units long, but think of it as a track of length, say 10,000, with the magnet pattern ... | def train_filter(iterations, kernel, sensor_accuracy,
move_distance, do_print=True):
track = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
prior = np.array([.9] + [0.01]*9)
posterior = prior[:]
normalize(prior)
robot = Train(len(track), kernel, sensor_accuracy)
for i in range(itera... | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
Read the code and make sure you understand it. Now let's do a run with no sensor or movement error. If the code is correct it should be able to locate the robot with no error. The output is a bit tedious to read, but if you are at all unsure of how the update/predict cycle works make sure you read through it carefully ... | import random
random.seed(3)
np.set_printoptions(precision=2, suppress=True, linewidth=60)
train_filter(4, kernel=[1.], sensor_accuracy=.999,
move_distance=4, do_print=True) | time 0: pos 4, sensed 4, at position 4
estimated position is 4 with confidence 99.9900%:
time 1: pos 8, sensed 8, at position 8
estimated position is 8 with confidence 100.0000%:
time 2: pos 2, sensed 2, at position 2
estimated position is 2 with confidence 100.0000%:
time 3: pos 6, sensed 6, at... | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
We can see that the code was able to perfectly track the robot so we should feel reasonably confident that the code is working. Now let's see how it fairs with some errors. 我们可以看到程序完美无误地实现了对机器人的跟踪,所以我们相当有信心相信代码在正常工作。现在我们来看一些失败案例和几个错误。 | random.seed(5)
train_filter(4, kernel=[.1, .8, .1], sensor_accuracy=.9,
move_distance=4, do_print=True) | time 0: pos 4, sensed 4, at position 4
estimated position is 4 with confidence 96.0390%:
time 1: pos 8, sensed 9, at position 8
estimated position is 9 with confidence 52.1180%:
time 2: pos 3, sensed 3, at position 3
estimated position is 3 with confidence 88.3993%:
time 3: pos 7, sensed 8, at p... | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
There was a sensing error at time 1, but we are still quite confident in our position. Now let's run a very long simulation and see how the filter responds to errors. 在时刻1有一个传感器异常,但我们仍然对预测的位置有相当高的置信度。现在加長模擬時間,看看滤波器是如何应对错误的。 | with figsize(y=5.5):
for i in range (4):
random.seed(3)
plt.subplot(221+i)
train_filter(148+i, kernel=[.1, .8, .1],
sensor_accuracy=.8,
move_distance=4, do_print=False)
plt.title (f'iteration {148 + i}') | _____no_output_____ | CC-BY-4.0 | 02-Discrete-Bayes.ipynb | anti-destiny/Kalman-and-Bayesian-Filters-in-Python |
House Prices: Advanced Regression TechniquesThis goal of this project was to predict sales prices and practice feature engineering, RFs, and gradient boosting. The dataset was part of the [House Prices Kaggle Competition](https://www.kaggle.com/c/house-prices-advanced-regression-techniques). Table of Contents* [1 Sum... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import missingno as msno
from time import time
from math import sqrt
import statsmodels.api as sm
from statsmodels.formula.api import ols
import scipy.stats as st
from scipy.special import boxcox1p
from sklearn.cluster import... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now, we read in the csv's as datarames into Python. | train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
3.2 Data StructureIn total, there are 81 columns/variables in the train dataset, including the response variable (SalePrice). I am only displaying a subset of the variables, as all of them will be discussed in more detail throughout the notebook.The train dataset consists of character and integer variables. Many of th... | print("Dimensions of Train Dataset:" + str(train.shape))
print("Dimensions of Test Dataset:" + str(test.shape))
train.iloc[:,0:10].info() | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Next, we are going to define a few variables that will be used in later analyses as well as being required for the submission file. | y_train = train['SalePrice']
test_id = test['Id']
ntrain = train.shape[0]
ntest = test.shape[0] | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Lastly, we are going to merge the train and test datasets to explore the data as well as impute any missing values. | all_data = pd.concat((train, test), sort=True).reset_index(drop=True)
all_data['Dataset'] = np.repeat(['Train', 'Test'], [ntrain, ntest], axis=0)
all_data.drop('Id', axis=1,inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
4 Exploring the Variables 4.1 Exploring the Response Variable: SalePrice The probability distribution plot show that the sale prices are right skewed. This is to be expected as few people can afford very expensive houses. | sns.set_style('whitegrid')
sns.distplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], axlabel="Normal Distribution", fit=st.norm, fit_kws={"color":"red"})
plt.title('Distribution of Sales Price in Dollars')
(mu, sigma) = st.norm.fit(train['SalePrice'])
plt.legend(['Normal Distribution \n ($\mu=$ {:.2f} and $... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Linear models tend to work better with normally distributed data. As such, we need to transform the response variable to make it more normally distributed. 4.2 Log-Transformation of the Response Variable | all_data['SalePrice'] = np.log1p(all_data['SalePrice'])
sns.distplot(all_data['SalePrice'][~all_data['SalePrice'].isnull()], axlabel="Normal Distribution", fit=st.norm, fit_kws={"color":"red"})
plt.title('Distribution of Transformed Sales Price in Dollars')
(mu, sigma) = st.norm.fit(train['SalePrice'])
plt.legend(['N... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
The skew is highly corrected and the distribution of the log-transformed sale prices appears more normally distributed. 5 Data Imputation 5.1 Completeness of the Data We first need to find which variables contain missing values. | cols_with_missing_values = all_data.isnull().sum().sort_values(ascending=False)
display(pd.DataFrame(cols_with_missing_values[cols_with_missing_values[cols_with_missing_values > 0].index],
columns=["Number of Missing Values"]))
cols_with_missing_values = all_data.isnull().sum().sort_values(ascendi... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
5.2 Impute the Missing Data 5.2.1 Missing Values Corresponding to Lack of Specific Feature * PoolQC: data description of the variables states that NA represents "no pool". This makes sense given the vast number of missing values (>99%) and that a majority of houses do not have a pool. | all_data['PoolQC'].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* MiscFeature: data description of the variables states that NA represents "no miscellaneous feature". | all_data['MiscFeature'].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Alley: data description of the variables states that NA represents "no alley access". | all_data['Alley'].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Fence: data description of the variables states that NA represents "no fence". | all_data['Fence'].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* FireplaceQU: data description of the variables states that NA represents "no fireplace". | all_data['FireplaceQu'].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* GarageType, GarageFinish, GarageQual, and GarageCond: Missing values are likely due to lack of a garage. Replacing missing data with None. | garage_categorical = ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']
for variable in garage_categorical:
all_data[variable].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* GarageYrBlt, GarageCars, and GarageArea: Missing values are likely due to lack of a basement. Replacing missing data with 0 (since no garage means no cars in a garage). | garage_numeric = ['GarageYrBlt', 'GarageCars', 'GarageArea']
for variable in garage_numeric:
all_data[variable].replace(np.nan, 0, regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* BsmtQual, BsmtCond, BsmtExposure, BsmtFinType1, and BsmtFinType2: Missing values are likely due to lack of a basement. Replacing missing data with None. | basement_categorical = ['BsmtQual','BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2']
for variable in basement_categorical:
all_data[variable].replace(np.nan, 'None', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* BsmtFinSF1, BsmtFinSF2, BsmtUnfSF, TotalBsmtSF, BsmtFullBath, and BsmtHalfBath: Missing values are likely due to lack of a basement. Replacing missing data with 0. | basement_numeric = ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath']
for variable in basement_numeric:
all_data[variable].replace(np.nan, 0, regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* MasVnrType and MasVnrArea: Missing values are likely due to lack of masonry vaneer. We will replace the missing values with None for the type and 0 for the area. | all_data['MasVnrType'].replace(np.nan, 'None', regex=True, inplace=True)
all_data['MasVnrArea'].replace(np.nan, 0, regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Functional: data description of the variables states that NA represents "typical". | all_data['Functional'].replace(np.nan, 'Typ', regex=True, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
5.2.2 Mode Imputation: Replacing Missing Values with Most Frequent Value Using a mode imputation, we replace the missing values of a categorical variable with the mode of the non-missing cases of that variable. While it does have the advantage of being fast, it comes at the cost of a reduction in variance within the d... | def mode_impute_and_plot(variable):
print('# of missing values: ' + str(all_data[variable].isna().sum()))
plt.figure(figsize=(8,4))
ax = sns.countplot(all_data[variable])
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
all_data[variable].r... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now we can proceed to replace the missing values for the following variables:[]() | ------|------[MSZoning](MSZoning) | [Utilities](Utilities) | [Electrical](Electrical) | [Exterior1st and Exterior2nd](Exterior1st and Exterior2nd) | [KitchenQual](KitchenQual) | [SaleType](SaleType) * MSZoning: "RL" is by far the most... | mode_impute_and_plot('MSZoning') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Utilities: With the exception of one "NoSeWa" value, all records for this variable are "AllPub". Since "NoSeWa" is only in the training set, this feature will not help in predictive modelling. As such, we can safely remove it. | mode_impute_and_plot('Utilities')
all_data = all_data.drop('Utilities', axis=1) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Electrical: Only one missing value, replace it with "SBrkr", the most common value. | mode_impute_and_plot('Electrical') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* Exterior1st and Exterior2nd: There is only one missing value for both Exterior 1 & 2. Missing values will be replaced by the most common value. | mode_impute_and_plot('Exterior1st')
mode_impute_and_plot('Exterior2nd') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* KitchenQual: Only one missing value, replace it with "TA", the most common value. | mode_impute_and_plot('KitchenQual') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
* SaleType: Replace missing values with "WD", the most common value. | mode_impute_and_plot('SaleType') | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Are there any remaining missing values? | cols_with_missing_values = all_data.isnull().sum().sort_values(ascending=False)
display(pd.DataFrame(cols_with_missing_values[cols_with_missing_values[cols_with_missing_values > 0].index], columns=["Number of Missing Values"]))
| _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Due to its numeric nature and the large number of missing values, the LotFrontage variable will be imputed separately using an SVM algorithm (See Section [7 LotFrontage Imputation](7-Lot-Frontage-Imputation)). The remaining variables are all complete! Now to move on to feature engineering. 6 Feature Engineering 6.1 ... | all_data['MixedConditions'] = all_data['Condition1'] + ' - ' + all_data['Condition2']
all_data.drop(labels=['Condition1', 'Condition2'], axis=1, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
6.2 Mixed ExteriorThe Exterior1st and Exterior2nd features are similar to the Conditions feature we merged and remove above. Properties with multiple types of exterior covering the house are assigned to Exterior1st or Exterior2nd alphabetically.As such, we will conduct the same process to merge the two columns into a ... | all_data['MixedExterior'] = all_data['Exterior1st'] + ' - ' + all_data['Exterior2nd']
all_data.drop(labels=['Exterior1st', 'Exterior2nd'], axis=1, inplace=True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
6.3 Total Square FeetOne of the important factors that people consider when buying a house is the total living space in square feet. Since the total square feet is not explicitly listed, we will add a new variable by adding up the square footage of the basement, first floor, and the second floor. | SF_df = all_data[['TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'SalePrice']]
SF_df = SF_df[~SF_df['SalePrice'].isnull()]
SF_vars = list(SF_df)
del SF_vars[-1]
SF_summary = []
for SF_type in SF_vars:
corr_val = np.corrcoef(SF_df[SF_type], SF_df['SalePrice'])[1][0]
SF_summary.append(corr_val)
pd.DataFrame([SF_su... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
There is a very strong correlation (r = 0.78) between the TotalSF and the SalePrice, with the exception of two outliers. These outliers should be removed to increase the accuracy of our model. 6.4 Total Number of BathroomsThere are 4 bathroom variables. Individually, these variables are not very important. Together, h... | bath_df = all_data[['BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'SalePrice']]
bath_df = bath_df[~bath_df['SalePrice'].isnull()]
bath_vars = list(bath_df)
del bath_vars[-1]
bath_summary = []
for bath_type in bath_vars:
corr_val = np.corrcoef(bath_df[bath_type], bath_df['SalePrice'])[1][0]
bath_summ... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
We can see a high positive correlation (r = 0.67) between TotalBath and SalePrice. The new variable correlation is much higher than any of the four original bathroom variables. 6.5 Binning the Neighbourhoods | neighborhood_prices = all_data.iloc[:ntrain].copy()
neighborhood_prices['SalePrice'] = np.exp(all_data['SalePrice'])
neighborhood_prices = neighborhood_prices[['Neighborhood', 'SalePrice']].groupby('Neighborhood').median().sort_values('SalePrice')
plt.figure(figsize=(15,7))
ax = sns.barplot(x= neighborhood_prices.inde... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
In order to bin the neighbourhoods into approriate clusters, we will use K-Mean clustering. K-Means is an unsupervised machine learning algorithm that groups a dataset into a user-specified number (k) of clusters. One potential issue with the algorithm is that it will cluster the data into k clusters, even if k is not ... | SS_distances = []
K = range(1,10)
for k in K:
km = KMeans(n_clusters=k)
km = km.fit(neighborhood_prices)
SS_distances.append(km.inertia_)
plt.plot(K, SS_distances, 'bx-')
plt.xlabel('k')
plt.ylabel('Sum of squared distances')
plt.title('Elbow Method For Optimal k')
plt.show() | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now let's see how the binned neighborhoods look like. | neighborhood_prices['Cluster'] = KMeans(n_clusters=3).fit(neighborhood_prices).labels_
plt.figure(figsize=(15,7))
ax = sns.barplot(x= neighborhood_prices.index, y=neighborhood_prices['SalePrice'],
hue=neighborhood_prices['Cluster'])
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
pl... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Lastly, we have to create a new variable in the dataset based on the new cluster labels. | neighborhood_dict = dict(zip(neighborhood_prices.index, neighborhood_prices.Cluster))
all_data['Neighborhood_Class'] = all_data['Neighborhood']
all_data['Neighborhood_Class'].replace(neighborhood_dict, inplace = True) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
7 LotFrontage ImputationDue to the numeric nature and sheer number of missing values in the LotFrontage column, we will impute the missing values using an SVM Regressor algorithm to predict the missing values.The first step is to subset the dataset into two groups. The train dataset (train_LotFrontage) contains the co... | train_LotFrontage = all_data[~all_data.LotFrontage.isnull()]
test_LotFrontage = all_data[all_data.LotFrontage.isnull()]
print("Dimensions of Train LotFrontage Dataset:" + str(train_LotFrontage.shape))
print("Dimensions of Test LotFrontage Dataset:" + str(test_LotFrontage.shape))
display(pd.DataFrame(all_data['LotFront... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now let's examine the distribution of LotFrontages values in the Train LotFrontage dataset through a boxplot and distribution plot. Through these graphs, we can see several interesting observations appear:* There is a cluster of low LotFrontage value properties, shown as a peak on the far left of the distribution plot.... | fig, ax = plt.subplots(1,2, figsize=(16,4))
sns.boxplot(train_LotFrontage['LotFrontage'], ax=ax[0])
sns.distplot(train_LotFrontage['LotFrontage'], ax=ax[1], fit=st.norm, fit_kws={"color":"red"})
(mu, sigma) = st.norm.fit(train_LotFrontage['LotFrontage'])
plt.legend(['Normal Distribution \n ($\mu=$ {:.2f} and $\sigma=... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
7.2 Outlier Detection & RemovalBefore we examine the correlations between LotFrontage and other variables, we should remove the outliers seen above. To do so, we will use the Interquartile Range (IQR) method, where values outside the Median ± 1.5IQR are considered to be outliers. These outliers are then removed from t... | def outlier_detection(data):
Q1, Q3 = np.percentile(data, [25,75])
IQR = Q3-Q1
lower_cutoff = Q1 - (IQR * 1.5)
upper_cutoff = Q3 + (IQR * 1.5)
outliers = (data > Q3+1.5*IQR) | (data < Q1-1.5*IQR)
return outliers
train_LotFrontage_no_outliers = train_LotFrontage[~outlier_detection(train_LotFronta... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Two new values previously not deemed outliers by the first iteration of the IQR range method are now shown as potential outliers in the boxplot. This is caused by having a new smaller IQR value after removing the first batch of outliers. As such, we will keep these values. 7.3 Determining Relevant Variables of LotFron... | temp_train = train_LotFrontage_no_outliers.copy()
temp_train.rename(columns={'1stFlrSF':'X1stFlrSF', '2ndFlrSF': 'X2ndFlrSF', '3SsnPorch': 'X3SsnPorch'}, inplace=True)
mod = ols('LotFrontage ~ X1stFlrSF + X2ndFlrSF + X3SsnPorch + Alley + BedroomAbvGr + BldgType + BsmtCond + BsmtExposure + BsmtFinSF1 + BsmtFinSF2 + Bsm... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
7.4 LotFrontage Model Building and EvaluationNow let's build a model using the relevant variables selected above. We will be using Support Vector Regressor to build the model.The first step is to seperate the target variable, LotFrontage, select the relevant variables, and dummifying the categorical variables. | X = train_LotFrontage_no_outliers[aov_table[aov_table['PR(>F)'] < 0.01].index]
y = train_LotFrontage_no_outliers['LotFrontage']
X = pd.get_dummies(X)
transformer = StandardScaler().fit(X)
X = transformer.transform(X) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
In order to determine the accuracy of our predictive model, we will create a Validation dataset. This dataset will have known values for the target LotFrontage variable which can we compare our model's prediction against. Using the mean absolute error, we can measure the difference between our predicted LotFrontage val... | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1234)
clf = svm.SVR(kernel='rbf', C=100, gamma=0.001)
clf.fit(X_train, y_train)
preds = clf.predict(X_test)
print('Mean Absolute Error: %.3f' % mean_absolute_error(y_test, preds)) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
These results show that using the SVR model to impute LotFrontage gives an average rror of less than 7 feet.We will now use the same SVR model to predict the unknown LotFrontage values in the test_Frontage dataset. | model_data = train_LotFrontage_no_outliers.copy()
model_data= model_data.append(test_LotFrontage)
y = model_data['LotFrontage']
model_data = model_data[['MSZoning', 'Alley', 'LotArea', 'LotShape', 'LotConfig', 'Neighborhood', 'MixedConditions', 'GarageType', 'GarageCars', 'GarageArea']]
model_data = pd.get_dummies(mod... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now that we have the newly predicted LotFrontage values, we can examine the distribution of predicted values relative to the known LotFrontage values in the training dataset. Both distributions have a mean around 70 feet with similar tail lengths on either end. | sns.distplot(model_y_train)
sns.distplot(LotFrontage_preds) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Lastly, we need to add the predicted values back into the original dataset. | all_data.LotFrontage[all_data.LotFrontage.isnull()] = LotFrontage_preds | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
8 Preparing the Data for Modelling 8.1 Removing OutliersAlthough we could be more in depth in our outliet detection and removal, we are only going to remove the two outliers found in the TotalSF variable. These properties exhibited large total square feet values with low SalePrice. | all_data.drop(all_data['TotalSF'].iloc[:ntrain].nlargest().index[:2], axis=0, inplace=True)
ntrain = train.shape[0]-2 | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
8.2 Correlation Between Numeric PredictorsWe can see a large correlation between many variables, suggesting a high level of multicollinearity. There are two options to consider:1. Use a regression model that deals well with multicollinearity, such as a ridge regression.2. Remove highly correlated predictors from the m... | corr = all_data.corr()
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
f, ax = plt.subplots(figsize=(15, 15))
cmap = sns.diverging_palette(220, 10, as_cmap=True)
sns.heatmap(corr, mask=mask, cmap=cmap,
center=0, square=True, linewidths = .5)
plt.show() | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
8.3 Label EncodingMany of the ordinal variables are presented as numeric values. Therefore we need to label encode these numeric characters into strings. | num_to_str_columns = ['MSSubClass', 'OverallQual', 'OverallCond', 'MoSold', 'YrSold']
for col in num_to_str_columns:
all_data[col] = all_data[col].astype('str')
cat_cols = ['OverallQual', 'OverallCond', 'ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1',
'BsmtFinType2', '... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
8.4 Skewness & Normalization of Numeric VariablesSkewness is a measure of asymmetry of a distribution, and can be used to define the extent to which the distribution differs from a normal distribution. Therefore, a normal distribution will have a skewness of 0. As a rule of thumb, if skewness is less than -1 or greate... | numeric_feats = ['LotFrontage', 'LotArea', 'BsmtFinSF1', 'BsmtUnfSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF',
'LowQualFinSF', 'GrLivArea', 'GarageArea', 'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch',
'3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal', 'TotalSF']
skewed_feats = all_data[... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
8.5 One Hot Encoding the Categorical VariablesThe last step needed to prepare the data is to make sure that all categorical predictor variables are converted into a form that is usable by machine learning algorithms. This process is known as 'one-hot encoding' the categorical variables.The process involved all non-ord... | all_data = pd.get_dummies(all_data)
print(all_data.shape)
all_data.head(3) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
9 SalePrice ModellingNow that the data is correctly processed, we are ready to begin building our predictive models. 9.1 Obtaining Final Train and Test Sets | final_y_train = all_data['SalePrice'][~all_data['SalePrice'].isnull()]
final_X_train = all_data[all_data['Dataset_Train'] == 1].drop(['Dataset_Train', 'Dataset_Test', 'SalePrice'], axis=1)
final_X_test = all_data[all_data['Dataset_Test'] == 1].drop(['Dataset_Train', 'Dataset_Test', 'SalePrice'], axis=1) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
9.2 Defining a Cross Validation StrategyWe will use the [cross_val_score](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_score.html) function of Sklearn and calculate the Root-Mean-Squared Error (RMSE) as a measure of accuracy. | n_folds = 10
def rmse_cv(model):
kf = KFold(n_folds, shuffle=True, random_state=1234).get_n_splits(final_X_train.values)
rmse= np.sqrt(-cross_val_score(model, final_X_train.values, final_y_train, scoring="neg_mean_squared_error", cv = kf))
return(rmse) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
9.3 Lasso Regression ModelThis model may be senstitive to outliers, so we need to make it more robust. This will be done using the RobustScaler function on pipeline. | lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.0005, random_state = 1234)) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Next, we tested out multiple alpha values and compared their accuracy using the rmse_cv function above. The results below show that using a value of 0.00025 is the optimal value of alpha for a Lasso Regression. | lasso_alpha = [1, 0.5, 0.25, 0.1, 0.05, 0.025, 0.01, 0.005, 0.0025, 0.001, 0.0005, 0.00025, 0.0001]
lasso_rmse = []
for value in lasso_alpha:
lasso = make_pipeline(RobustScaler(), Lasso(alpha = value, max_iter=3000, random_state = 1234))
lasso_rmse.append(rmse_cv(lasso).mean())
lasso_score_table = pd.Data... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Using the newly defined alpha value, we can optimize the model and predict the missing values of SalePrice. The predictions are then formatted in a appropriate layout for submission to Kaggle. | lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.00025, random_state = 1234))
lasso.fit(final_X_train, final_y_train)
lasso_preds = np.expm1(lasso.predict(final_X_test))
sub = pd.DataFrame()
sub['Id'] = test_id
sub['SalePrice'] = lasso_preds
#sub.to_csv('Lasso Submission 2.csv',index=False) | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
LASSO Regression Score: 0.12679 9.4 Ridge Regression ModelIdentical steps were taken for the ridge regression model as we took for the [Lasso Regression Model](9.3-Lasso-Regression-Model). In the case of the Ridge model, the optimal alpha value was 6. | ridge_alpha = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
ridge_rmse = []
for value in ridge_alpha:
ridge = make_pipeline(RobustScaler(), Ridge(alpha = value, random_state = 1234))
ridge_rmse.append(rmse_cv(ridge).mean())
ridge_score_table = pd.DataFrame(ridge_rmse,ridge_alpha,columns=['RMSE'])
display(ridge_sc... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Ridge Regression Score: 0.12528 9.5 XGBoost ModelSince there are multiple hyperparameters to tune in the XGBoost model, we will use the [GridSearchCV](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) function of Sklearn to determine the optimal values. Next, I used the [trai... | xg_X_train, xg_X_test, xg_y_train, xg_y_test = train_test_split(final_X_train, final_y_train, test_size=0.33, random_state=1234)
xg_model = XGBRegressor(n_estimators=100, seed = 1234)
param_dict = {'max_depth': [3,4,5],
'min_child_weight': [2,3,4],
'learning_rate': [0.05, 0.1,0.15],
... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Now that the hyperparameter have been chosen, we can calculate the validation RMSE of the XGBoost model. | xg_model = XGBRegressor(n_estimators = 1000,
learning_rate = 0.1,
max_depth = 4,
min_child_weight = 4,
gamma = 0,
seed = 1234)
start = time()
xg_model.fit(xg_X_train, xg_y_train)
xg_preds = xg_model.p... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Lastly, we predict the SalePrice using the test data. The predictions are then formatted in a appropriate layout for submission to Kaggle. | xg_model = XGBRegressor(n_estimators = 1000,
learning_rate = 0.1,
max_depth = 4,
min_child_weight = 4,
gamma = 0,
seed = 1234)
xg_model.fit(final_X_train, final_y_train)
xg_preds = np.expm1(xg_model.p... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
XGBoost Regression Model: 0.12799 9.6 Ensemble ModelSince the Lasso, Ridge, XGBoost algorithms so different, averaging the final Saleprice predictions may improve the accuracy. Since the Ridge regression performed the best with regards to the final RMSE (0.125 vs 0.126 and 0.127), I will assign it's weight to be doub... | lasso = make_pipeline(RobustScaler(), Lasso(alpha = 0.00025, random_state = 1234))
lasso.fit(final_X_train, final_y_train)
lasso_preds = np.expm1(lasso.predict(final_X_test))
ridge = make_pipeline(RobustScaler(), Ridge(alpha = 6, random_state = 1234))
ridge.fit(final_X_train, final_y_train)
ridge_preds = np.expm1(ridg... | _____no_output_____ | Apache-2.0 | GAN Model/eda-to-ensemble-model-lasso-ridge-xgboost.ipynb | MrTONYCHAN/xyz |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.