markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Calculate the RMSE. You should be able to get around 100,000 RMSE (remember that this is in the same units as the label.) Do this manually or use sklearn.metrics | final_pred = []
for pred in precitions:
final_pred.append(pred['predictions'])
from sklearn.metrics import mean_squared_error, mean_absolute_error
# RMSE = sqrt(MSE) = MSE ** 0.5
mean_squared_error(Y_test, final_pred) ** 0.5 | 18-05-28-Complete-Guide-to-Tensorflow-for-Deep-Learning-with-Python/02-Tensorflow-Basics/06-Regression-Exercise.ipynb | arcyfelix/Courses | apache-2.0 |
Download & Process Security Dataset | sd_file = "https://raw.githubusercontent.com/OTRF/Security-Datasets/master/datasets/atomic/windows/execution/host/empire_launcher_vbs.zip"
registerMordorSQLTable(spark, sd_file, "sdTable") | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic I
Within the classic PowerShell log, event ID 400 indicates when a new PowerShell host process has started. You can filter on powershell.exe as a host application if you want to or leave it without a filter to capture every single PowerShell host
| Data source | Event Provider | Relationship | Event |
|:------... | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, Channel
FROM sdTable
WHERE (Channel = "Microsoft-Windows-PowerShell/Operational" OR Channel = "Windows PowerShell")
AND (EventID = 400 OR EventID = 4103)
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic II
Looking for non-interactive powershell session might be a sign of PowerShell being executed by another application in the background
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Process | Microsoft-Windows-Security-Auditing | Process creat... | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, NewProcessName, ParentProcessName
FROM sdTable
WHERE LOWER(Channel) = "security"
AND EventID = 4688
AND NewProcessName LIKE "%powershell.exe"
AND NOT ParentProcessName LIKE "%explorer.exe"
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic III
Looking for non-interactive powershell session might be a sign of PowerShell being executed by another application in the background
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Process | Microsoft-Windows-Sysmon/Operational | Process cre... | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, Image, ParentImage
FROM sdTable
WHERE Channel = "Microsoft-Windows-Sysmon/Operational"
AND EventID = 1
AND Image LIKE "%powershell.exe"
AND NOT ParentImage LIKE "%explorer.exe"
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic IV
Monitor for processes loading PowerShell DLL system.management.automation
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Module | Microsoft-Windows-Sysmon/Operational | Process loaded Dll | 7 | | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, Image, ImageLoaded
FROM sdTable
WHERE Channel = "Microsoft-Windows-Sysmon/Operational"
AND EventID = 7
AND (lower(Description) = "system.management.automation" OR lower(ImageLoaded) LIKE "%system.management.automation%")
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic V
Monitoring for PSHost* pipes is another interesting way to find PowerShell execution
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Named Pipe | Microsoft-Windows-Sysmon/Operational | Process created Pipe | 17 | | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, Image, PipeName
FROM sdTable
WHERE Channel = "Microsoft-Windows-Sysmon/Operational"
AND EventID = 17
AND lower(PipeName) LIKE "\\\\pshost%"
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Analytic VI
The "PowerShell Named Pipe IPC" event will indicate the name of the PowerShell AppDomain that started. Sign of PowerShell execution
| Data source | Event Provider | Relationship | Event |
|:------------|:---------------|--------------|-------|
| Powershell | Microsoft-Windows-PowerShell/Operational | Applic... | df = spark.sql(
'''
SELECT `@timestamp`, Hostname, Message
FROM sdTable
WHERE Channel = "Microsoft-Windows-PowerShell/Operational"
AND EventID = 53504
'''
)
df.show(10,False) | docs/notebooks/windows/02_execution/WIN-190410151110.ipynb | VVard0g/ThreatHunter-Playbook | mit |
Parameters are given as follows. D and radius mean a diffusion constant and a radius of molecules, respectively. Dimensions of length and time are assumed to be micro-meter and second. | D = 1 # 0.01
radius = 0.005
N = 20 # a number of samples
y0 = {} # {'A': 60}
duration = 3
V = 8 | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Make a model for all algorithms. No birth reaction with more than one product is accepted. | with species_attributes():
A | {'radius': radius, 'D': D}
with reaction_rules():
~A > A | 45.0
A > ~A | 1.5
m = get_model() | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Save a result with ode as obs, and plot it: | ret1 = run_simulation(duration, y0=y0, volume=V, model=m)
ret1 | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Simulating with gillespie (Bars represent standard error of the mean): | ret2 = ensemble_simulations(duration, ndiv=20, y0=y0, volume=V, model=m, solver='gillespie', repeat=N)
ret2.plot('o', ret1, '-') | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Simulating with meso: | ret2 = ensemble_simulations(
duration, ndiv=20, y0=y0, volume=V, model=m, solver=('meso', Integer3(3, 3, 3), 0.25), repeat=N)
ret2.plot('o', ret1, '-') | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Simulating with spatiocyte: | ret2 = ensemble_simulations(
duration, ndiv=20, y0=y0, volume=V, model=m, solver=('spatiocyte', radius), repeat=N)
ret2.plot('o', ret1, '-') | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Simulating with egfrd: | ret2 = ensemble_simulations(
duration, ndiv=20, y0=y0, volume=V, model=m, solver=('egfrd', Integer3(8, 8, 8)), repeat=N)
ret2.plot('o', ret1, '-') | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
Simulating with bd: | ret2 = ensemble_simulations(
duration, ndiv=20, y0=y0, volume=V, model=m, solver=('bd', Integer3(8, 8, 8), 0.1), repeat=N)
ret2.plot('o', ret1, '-') | en/tests/Birth_Death.ipynb | ecell/ecell4-notebooks | gpl-2.0 |
We can apply the LinearSVC model to a synthetic dataset, and visualize the decision boundary: | from sklearn.svm import LinearSVC
X, y = make_forge()
model = LinearSVC()
clf = model.fit(X,y)
plot_2d_separator(clf, X, fill=False, eps=0.5, alpha=.7)
discrete_scatter(X[:, 0], X[:, 1], y)
plt.title("{}".format(clf.__class__.__name__))
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.legend() | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
In this figure, we have the first feature of the dataset on the x-axis and the second feature on the y-axis. We display the decision boundary found by LinearSVC as a straight line, separating the area classified as class 1 on the top from the area classified as class 0 on the bottom. In other words, any new data point ... | from sklearn.svm import SVC
def plot_linear_svc_regularization():
X, y = make_blobs(centers=2, random_state=4, n_samples=30)
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
# a carefully hand-designed dataset lol
y[7] = 0
y[27] = 0
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_mi... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
On the lefthand side, we have a very small C corresponding to a lot of regularization. Most of the points in class 0 are at the top, and most of the points in class 1 are at the bottom. The strongly regularized model chooses a relatively horizontal line, misclassifying two points. In the center plot, C is slightly high... | X, y = make_blobs(centers=3, random_state=42)
discrete_scatter(X[:, 0], X[:, 1], y, c=['b', 'r', 'g'])
plt.xlabel("Feature 0")
plt.ylabel("Feature 1")
plt.legend(["Class 0", "Class 1", "Class 2"]) | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Now, we train a LinearSVC classifier on the dataset: | linear_svm = LinearSVC().fit(X, y)
print("Coefficient shape: ", linear_svm.coef_.shape)
print("Intercept shape: ", linear_svm.intercept_.shape) | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
We see that the shape of the coef_ is (3, 2), meaning that each row of coef_ contains the coefficient vector for one of the three classes and each column holds the coefficient value for a specific feature (there are two in this dataset). The intercept_ is now a one-dimensional array, storing the intercepts for each cla... | discrete_scatter(X[:, 0], X[:, 1], y, c=['b', 'r', 'g'])
line = np.linspace(-15, 15)
for coef, intercept, color in zip(linear_svm.coef_, linear_svm.intercept_, ['b', 'r', 'g']):
plt.plot(line, -(line * coef[0] + intercept) / coef[1], c=color)
plt.ylim(-10, 15)
plt.xlim(-10, 8)
plt.xlabel("Feature 0")
plt.ylabel("Fe... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
You can see that all the points belonging to class 0 in the training data are above the line corresponding to class 0, which means they are on the “class 0” side of this binary classifier. The points in class 0 are above the line corresponding to class 2, which means they are classified as “rest” by the binary classifi... | cm3 = ListedColormap(['#0000aa', '#ff2020', '#50ff50'])
def plot_2d_classification(classifier, X, fill=False, ax=None, eps=None, alpha=1, cm=cm3):
# multiclass
if eps is None:
eps = X.std() / 2.
if ax is None:
ax = plt.gca()
x_min, x_max = X[:, 0].min() - eps, X[:, 0].max() + eps
... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Kernelized Support Vector Machines
Kernelized support vector machines (often just referred to as SVMs) are an extension that allows for more complex models that are not defined simply by hyperplanes in the input space. While there are support vector machines for classification and regression, we will restrict ourselves... | c=['b', 'r', 'g']
X, y = make_blobs(centers=4, random_state=8)
y = y % 2
discrete_scatter(X[:, 0], X[:, 1], y, c=c)
plt.xlabel("Feature 0")
plt.ylabel("Feature 1") | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
A linear model for classification can only separate points using a line, and will not be able to do a very good job on this dataset: | from sklearn.svm import LinearSVC
linear_svm = LinearSVC().fit(X, y)
plot_2d_separator(linear_svm, X)
discrete_scatter(X[:, 0], X[:, 1], y, c=c)
plt.xlabel("Feature 0")
plt.ylabel("Feature 1") | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Now let’s expand the set of input features, say by also adding feature1^2, the square of the second feature, as a new feature. Instead of representing each data point as a two-dimensional point, (feature0, feature1), we now represent it as a three-dimensional point, (feature0, feature1, feature1^22). This new represent... | # add the squared first feature
X_new = np.hstack([X, X[:, 1:] ** 2])
from mpl_toolkits.mplot3d import Axes3D, axes3d
figure = plt.figure()
# visualize in 3D
ax = Axes3D(figure, elev=-152, azim=-26)
# plot first all the points with y == 0, then all with y == 1
mask = y == 0
ax.scatter(X_new[mask, 0], X_new[mask, 1], X... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
In the new representation of the data, it is now indeed possible to separate the two classes using a linear model, a plane in three dimensions. We can confirm this by fitting a linear model to the augmented data: | linear_svm_3d = LinearSVC().fit(X_new, y)
coef, intercept = linear_svm_3d.coef_.ravel(), linear_svm_3d.intercept_
# show linear decision boundary
figure = plt.figure()
ax = Axes3D(figure, elev=-152, azim=-26)
xx = np.linspace(X_new[:, 0].min() - 2, X_new[:, 0].max() + 2, 50)
yy = np.linspace(X_new[:, 1].min() - 2, X_n... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
As a function of the original features, the linear SVM model is not actually linear anymore. It is not a line, but more of an ellipse, as you can see from the plot created here: | ZZ = YY ** 2
dec = linear_svm_3d.decision_function(np.c_[XX.ravel(), YY.ravel(), ZZ.ravel()])
plt.contourf(XX, YY, dec.reshape(XX.shape), levels=[dec.min(), 0, dec.max()], cmap=cm2, alpha=0.5)
discrete_scatter(X[:, 0], X[:, 1], y, c=c)
plt.xlabel("Feature 0")
plt.ylabel("Feature 1") | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
The kernel trick
The lesson here is that adding nonlinear features to the representation of our data can make linear models much more powerful. However, often we don’t know which features to add, and adding many features (like all possible interactions in a 100-dimensional feature space) might make computation very exp... | def make_handcrafted_dataset():
# a carefully hand-designed dataset lol
X, y = make_blobs(centers=2, random_state=4, n_samples=30)
y[np.array([7, 27])] = 0
mask = np.ones(len(X), dtype=np.bool)
mask[np.array([0, 1, 5, 26])] = 0
X, y = X[mask], y[mask]
return X, y
from sklearn.svm import SVC... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
In this case, the SVM yields a very smooth and nonlinear (not a straight line) boundary. We adjusted two parameters here: the C parameter and the gamma parameter, which we will now discuss in detail.
Tuning SVM parameters
The gamma parameter is the one shown in the formula given in the previous section, which controls ... | def plot_svm(log_C, log_gamma, ax=None):
X, y = make_handcrafted_dataset()
C = 10. ** log_C
gamma = 10. ** log_gamma
svm = SVC(kernel='rbf', C=C, gamma=gamma).fit(X, y)
if ax is None:
ax = plt.gca()
plot_2d_separator(svm, X, ax=ax, eps=.5)
# plot data
discrete_scatter(X[:, 0], X[... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Going from left to right, we increase the value of the parameter gamma from 0.1 to 10. A small gamma means a large radius for the Gaussian kernel, which means that many points are considered close by. This is reflected in very smooth decision boundaries on the left, and boundaries that focus more on single points furth... | from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=0)
svc = SVC()
svc.fit(X_train, y_train)
print("Accuracy on training set: {:.2f}".format(svc... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
The model overfits quite substantially, with a perfect score on the training set and only 63% accuracy on the test set. While SVMs often perform quite well, they are very sensitive to the settings of the parameters and to the scaling of the data. In particular, they require all the features to vary on a similar scale. ... | plt.plot(X_train.min(axis=0), 'o', label="min")
plt.plot(X_train.max(axis=0), '^', label="max")
plt.legend(loc=4)
plt.xlabel("Feature index")
plt.ylabel("Feature magnitude")
plt.yscale("log") | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
From this plot we can determine that features in the Breast Cancer dataset are of completely different orders of magnitude. This can be somewhat of a problem for other models (like linear models), but it has devastating effects for the kernel SVM. Let’s examine some ways to deal with this issue.
Preprocessing data for ... | from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
svc = SVC()
svc.fit(X_train_scaled, y_train)
print("Accuracy on training set: {:.3f}".format(svc.score(X_train_scaled, y_train)))
print("Accu... | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Scaling the data made a huge difference! Now we are actually in an underfitting regime, where training and test set performance are quite similar but less close to 100% accuracy. From here, we can try increasing either C or gamma to fit a more complex model. For example: | svc = SVC(C=1000)
svc.fit(X_train_scaled, y_train)
print("Accuracy on training set: {:.3f}".format(svc.score(X_train_scaled, y_train)))
print("Accuracy on test set: {:.3f}".format(svc.score(X_test_scaled, y_test))) | SL6_Kernel_Methods_and_SVMs.ipynb | tleonhardt/machine_learning | apache-2.0 |
Interactive Features
zoom/pan
reorder rows and columns using buttons or by double-clicking row/column/category names
interactively perform dimensionality reduction (and re-clustering) using row-filter sliders (e.g. filter rows based on variance)
identify clusters of varying sizes using the interactive row and column d... | import numpy as np
import pandas as pd
# generate random matrix
num_rows = 500
num_cols = 10
np.random.seed(seed=100)
mat = np.random.rand(num_rows, num_cols)
# make row and col labels
rows = range(num_rows)
cols = range(num_cols)
rows = [str(i) for i in rows]
cols = [str(i) for i in cols]
# make dataframe
df = pd.... | Running_clustergrammer_widget.ipynb | MaayanLab/clustergrammer-widget | mit |
Initialize the network object, load the dataframe, hierarchically cluster the rows and columns using default parameters, and finally visualize using clustergrammer_widget. | net.load_df(df)
net.cluster(enrichrgram=False)
net.widget() | Running_clustergrammer_widget.ipynb | MaayanLab/clustergrammer-widget | mit |
Convolutional Wasserstein Barycenter example
This example is designed to illustrate how the Convolutional Wasserstein Barycenter
function of POT works. | # Author: Nicolas Courty <ncourty@irisa.fr>
#
# License: MIT License
import numpy as np
import pylab as pl
import ot | docs/source/auto_examples/plot_convolutional_barycenter.ipynb | rflamary/POT | mit |
Data preparation
The four distributions are constructed from 4 simple images | f1 = 1 - pl.imread('../data/redcross.png')[:, :, 2]
f2 = 1 - pl.imread('../data/duck.png')[:, :, 2]
f3 = 1 - pl.imread('../data/heart.png')[:, :, 2]
f4 = 1 - pl.imread('../data/tooth.png')[:, :, 2]
A = []
f1 = f1 / np.sum(f1)
f2 = f2 / np.sum(f2)
f3 = f3 / np.sum(f3)
f4 = f4 / np.sum(f4)
A.append(f1)
A.append(f2)
A.ap... | docs/source/auto_examples/plot_convolutional_barycenter.ipynb | rflamary/POT | mit |
Barycenter computation and visualization | pl.figure(figsize=(10, 10))
pl.title('Convolutional Wasserstein Barycenters in POT')
cm = 'Blues'
# regularization parameter
reg = 0.004
for i in range(nb_images):
for j in range(nb_images):
pl.subplot(nb_images, nb_images, i * nb_images + j + 1)
tx = float(i) / (nb_images - 1)
ty = float(j)... | docs/source/auto_examples/plot_convolutional_barycenter.ipynb | rflamary/POT | mit |
Fill in your event data
Put in your message, date and timestamp description | #message: A string that will be used as the message string.
message = "" #@param {type:"string"}
#date: A string with the timestamp of the message.
# This should be in a human readable format, eg: "2020-09-03T22:52:21".
# if empty it will set to now
date = "2020-08-06T12:48:06.994188Z" #@param {type:"string"}
#t... | notebooks/add_a_single_event_to_a_sketch.ipynb | google/timesketch | apache-2.0 |
Attributes / Tags (optional)
Fill in additional attributes and tags
If you do not need that, empty them.
Examples:
attributes: A dict of extra attributes to add to the event.
attributes = {"a": "alpha", "o": "omega", "g": "gamma"}
tags: A list of strings to include as tags.
tags = ["not", "important"] | #attributes: A dict of extra attributes to add to the event.
attributes = {"a": "alpha", "o": "omega", "g": "gamma"}
#tags: A list of strings to include as tags.
tags = ["not", "important"]
sketch.add_event(message, date, timestamp_desc, attributes, tags) | notebooks/add_a_single_event_to_a_sketch.ipynb | google/timesketch | apache-2.0 |
We then initialize the SA and specify the output filename and output cadence. We can choose the output interval to either correspond to constant intervals in walltime (in seconds) or simulation time. Here, we choose walltime. To choose simulation time instead replace the walltime argument with interval. | sim.automateSimulationArchive("simulationarchive.bin", walltime=1.,deletefile=True) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
Now, we can run the simulation forward in time. | sim.integrate(2e5) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
Depending on how fast your computer is, the above command may take a couple of seconds. Once the simulation is done, we can delete it from memory and load it back in from the SA. You could do this at a later time. Note that this will even work if the SA file was generated on a different computer with a different operat... | sim = None
sim = rebound.Simulation("simulationarchive.bin")
print("Time after loading simulation %.1f" %sim.t) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
If we want to integrate the simulation further in time and append snapshots to the same SA, then we need to call the automateSimulationArchive method again (this is fail safe mechanism to avoid accidentally modifying a SA file). Note that we set the deletefile flag to False. Otherwise we would create a new empty SA fil... | sim.automateSimulationArchive("simulationarchive.bin", walltime=1.,deletefile=False) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
Now, let's integrate the simulation further in time. | sim.integrate(sim.t+2e5) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
If we repeat the process, one can see that the SA binary file now includes the new snapshots from the restarted simulation. | sim = None
sim = rebound.Simulation("simulationarchive.bin")
print("Time after loading simulation %.1f" %sim.t) | ipython_examples/SimulationArchiveRestart.ipynb | dtamayo/rebound | gpl-3.0 |
First things first, let's set up up the database to regress. | x = np.linspace(-np.pi,np.pi,100)
x_pred = np.linspace(-1.5*np.pi,1.5*np.pi,200)
epsilon = stats.norm(loc=0,scale=0.01)
noise = epsilon.rvs(size=x.shape[0])
t = np.exp(-x**2) + noise
fig = plt.figure(figsize=(5,5))
plt.plot(x,t,'ro',markerfacecolor="None",label="data")
plt.xlabel("input")
plt.ylabel("output")
plt.lege... | Tutorial.ipynb | Hamstard/RVMs | mit |
1. Single Regression
1.1 Linear Kernel
Neat now let's test whether we can regress that data using a polynomial feature space. | # choosing the feature space
k = 5
trafo = preprocessing.PolynomialFeatures(k)
X = trafo.fit_transform(x.reshape((-1,1)))
# initializing hyperparameters
init_beta = 1./ np.var(t) # (that's the default start)
init_alphas = np.ones(X.shape[1])
init_alphas[1:] = np.inf
# setting up the model regression class
model = Rel... | Tutorial.ipynb | Hamstard/RVMs | mit |
1.2 Localized Kernel
Indeed that seemed to work. But what about a Gaussian feature space, will it be able to fit the Gaussian? | # choosing the feature space
trafo = GaussianFeatures(k=30,mu0=-3,dmu=.2)
X = trafo.fit_transform(x.reshape((-1,1)))
# initializing hyperparameters
init_beta = 1./ np.var(t) # (that's the default start)
init_alphas = np.ones(X.shape[1])
init_alphas[1:] = np.inf
# setting up the model regression class
model = Relevanc... | Tutorial.ipynb | Hamstard/RVMs | mit |
2. Repeated Regressions
Indeed using a Gaussian basis set, for some mysterious reason, gave a closer estimate to the real data with tighter confidence intervals. Now let's do the same again for both kernels but multiple times initializing the hyperparmaeters such that we sample them from distributions as well.
2.1 Line... | # choosing the feature space
k = 5
trafo = preprocessing.PolynomialFeatures(k)
X = trafo.fit_transform(x.reshape((-1,1)))
base_trafo = trafo.fit_transform
# initializing hyperparameters using callable distributions giving new hyperparameters
# with every call (useful for repeated regression)
init_beta = distribution_w... | Tutorial.ipynb | Hamstard/RVMs | mit |
2.2 Localized kernel | # choosing the feature space
trafo = GaussianFeatures(k=30,mu0=-3,dmu=.2)
base_trafo = trafo.fit_transform
# initializing hyperparameters using callable distributions giving new hyperparameters
# with every call (useful for repeated regression)
init_beta = distribution_wrapper(stats.halfnorm(scale=1),size=1,single=Tru... | Tutorial.ipynb | Hamstard/RVMs | mit |
Importing it takes some time
Has many functions like read_csv and uniq that help a lot | import numpy as np | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
05 - NumPy Arrays
Both Pandas and NumPy have special data structures for 1 D data
Numpy array is similar to Python list
Similarities
Access element by index
Access a range of elements
Use loops
Differences
Each element should have same type
Can have different types but it was designed for single data type
Convenien... | employments = pd.read_csv('employment_above_15.csv')
employments[0:5]
#Selecting a column and displaying its first 5 elements
employments.get('1991')[0:5]
employments.get('Country')[0:5]
def max_employment(countries, employment):
i = employment.argmax()
return (countries[i], employment[i])
max_employme... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
Let's look at the element type of few array which numpy calls dtype | countries = np.array(['Afghanistan','Albania','Algeria','Angola','Argentina','Armenia'])
employment = np.array([56.700001, 52.700001, 39.400002, 75.800003, 53.599998])
print countries.dtype
print employment.dtype
print np.array([0, 1, 2, 3]).dtype
print np.array([True, False, True]).dtype
print np.array(['AL', 'AK'])... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
|S11 means String with maximum length 11. | print employment.mean()
print employment.std()
print employment.max()
print employment.sum() | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
07 - Vectorized Operations
Numpy supports Vectorized operations
A vector is a list of numbers
Addition of 2 vectors can be done in several ways. Different languages implement it differently
In case of NumPy it is an element wise addition | np.array([1, 2, 3]) + np.array([4, 5, 6]) | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
09 - Multiplying by a Scalar
Multiplying by Scalar is scalar multiplied with each element of the array | np.array([1, 2, 3]) * 3 | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
11 - Calculate Overall Completion Rate
More vectorized operations | np.array([1, 2, 3]) + np.array([4, 5, 6])
np.array([1, 2, 3]) + 1
np.array([1, 2, 3]) - np.array([7, 10, 15])
np.array([1, 2, 3]) - 1
np.array([1, 2, 3]) * np.array([4, 5, 6])
np.array([1, 2, 3]) * np.array([2])
#Throws error
#np.array([1, 2, 3]) * np.array([2, 3])
np.array([2, 3]) ** np.array([2, 3])
np.array(... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
See this article for more information about bitwise operations.
In NumPy, a & b performs a bitwise and of a and b. This is not necessarily the same as a logical and, if you wanted to see if matching terms in two integer vectors were non-zero. However, if a and b are both arrays of booleans, rather than integers, bi... | female_completion = pd.read_csv('female_completion_rate.csv')
male_completion = pd.read_csv('male_completion_rate.csv')
female_completion[0:5]
male_completion[0:5]
female = np.array([56.0, 23.0, 65.0])
male = np.array([23.0, 45.0, 22.0])
def overall_completion_rate(female_completion, male_completion):
return (f... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
13 - Standardizing Data
How does one data point compare to other data point?
One way to do this is to convert the data point to number of standard deviations from the mean | def standardize_data(values):
return (values - values.mean()) / values.std() | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
15 - NumPy Index Arrays | def mean_time_for_paid_students(time_spent, days_to_cancel):
return time_spent[days_to_cancel >= 7].mean() | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
17 - + vs += | a = np.array([1, 2, 3, 4])
b = a
a += np.array([1, 1, 1, 1]) #Difference here
print b | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
a = np.array([1, 2, 3, 4])
b = a
a = a + np.array([1, 1, 1, 1]) #Difference here
print b | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit | |
19 - In-Place vs Not In-Place
+= operates in-place while + does not | a = np.array([1, 2, 3, 4, 5])
slice = a[:3]
slice[0] = 100
a | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
slice refers to view of original array
21 - Pandas Series | def variable_correlation(variable1, variable2):
both_above = (variable1 > variable1.mean()) & \
(variable2 > variable2.mean())
both_below = (variable1 < variable1.mean()) & \
(variable2 < variable2.mean())
is_same_direction = both_above | both_below
num_same_direct... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
23 - Series Indexes | s = pd.Series([1, 2, 3, 4])
s.describe()
countries = np.array(['Albania', 'Algeria', 'Andorra', 'Angola'])
life_expectancy = np.array([74.7, 75., 83.4, 57.6])
life_expectancy | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
Some people call countries[0] as indexing into array. But the instructor uses position 0 to avoid confusion. This is because in Pandas index and postion are not the same thing | life_expectancy = pd.Series([74.7, 75., 83.4, 57.6],
index = ['Albania',
'Algeria',
'Andorra',
'Angola'])
life_expectancy | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
NumPy arrays are souped-up version of Python lists
Pandas Series is like a cross between a list and a dictionary | #Access by index
life_expectancy.loc['Angola']
#If we don't specify index then automatically adds index 0, 1, 2, ...
pd.Series([74.7, 75., 83.4, 57.6])
#Access element by position
print life_expectancy.iloc[0]
#same as
print life_expectancy[0]
def max_employment(employment):
max_country = employment.argmax()
... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
25 - Vectorized Operations and Series Indexes
In NumPy arrays addition happens as per position
What happens if we add two Pandas series? | s1 = pd.Series([1, 2, 3, 4], index = ['a', 'b', 'c', 'd'])
s2 = pd.Series([10, 20, 30, 40], index = ['a', 'b', 'c', 'd'])
s1
s2
s1 + s2
# Index are in different order
s3 = pd.Series([10, 20, 30, 40], index = ['b', 'd', 'a', 'c'])
s3
s1 + s3 | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
Matching indexes were used to add the 2 series | s4 = pd.Series([10, 20, 30, 40], index = ['c', 'd', 'e', 'f'])
s4
s1 + s4
#If we don't want to show NaN in our solution
(s1 + s4).dropna() | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
28 - Filling Missing Values - Solution | #If we want to give a default value
s1.add(s4, fill_value=0) | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
29 - Pandas Series apply
So far we have used built-in functions like mean() and vectorized operations like +
apply takes a Series and a function and returns a new series applying the function on each element of the Series | names = pd.Series([
'Andre Agassi',
'Barry Bonds',
'Christopher Columbus',
'Daniel Defoe'
])
def reverse_name(name):
split_name = name.split(" ")
return "{}, {}".format(split_name[1], split_name[0])
reverse_name(names.iloc[0])
def reverse_names(names):
return names.app... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
31 - Plotting in Pandas - Solution | employment = pd.read_csv('employment_above_15.csv', index_col = 'Country')
female_completion = pd.read_csv('female_completion_rate.csv', index_col = 'Country')
male_completion = pd.read_csv('male_completion_rate.csv', index_col = 'Country')
life_expectancy = pd.read_csv('life_expectancy.csv', index_col = 'Country')
gdp... | udacity_data_science_notes/intro_data_analysis/lesson_02/Lesson2.ipynb | anshbansal/anshbansal.github.io | mit |
$$ E(m) = m^e (mod(n)) $$ | d, n = 17,403 # закрытый ключ
D = lambda c: (pow(c,d))%n # расшифрование | RSA.ipynb | TeamProgramming/testsPy | mit |
$$ D(c) = c^d (mod(n)) $$ | p, q = 23, 17
phi(n) | RSA.ipynb | TeamProgramming/testsPy | mit |
$$ p(360) = p(40)p(9) = 6p(5)p(8) = 64*4 = 96 $$
$$ d\cdot e\equiv 1{\pmod {\varphi (n)}} $$ | print ( (e*d)%phi(n))
e*d | RSA.ipynb | TeamProgramming/testsPy | mit |
обратный элемент
$$a^{-1} \equiv a^{\varphi(n)-1} \pmod n, если { \displaystyle (a,n)=1.} (a,n) = 1. $$
$$ e = d^{\phi(\phi(n))-1} mod(\phi(n))$$ | a_1 = lambda a,n: pow(a,phi(n)-1)%n
e = a_1(d,phi(n))
def strRSA(msg):
for m in msg:
print(m+" = "+str(ru[m]) + " RSA = "+str(E(ru[m])))
strRSA('жопа') | RSA.ipynb | TeamProgramming/testsPy | mit |
<hr>
<h2>Pregunta 2</h2>
Usando como parámetros de entrada:
<ul>
<li>Edad = 10.5 Gyr</li>
<li>Fe/H = -1.56</li>
<li>Distancia = 61KPc</li>
<li>$A_V = 0.1272$</li>
</ul> | from isochrones.dartmouth import Dartmouth_Isochrone
iso = Dartmouth_Isochrone(bands=['V','I'])
model = iso.isochrone(age=10.021189299,feh=-1.56,distance=61000,AV=0.1272,dm=1e-5)
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim(-0.5,1.5)
ax.set_ylim(24,16)
ax.set_xlabel('$V-I$',fontsize=20)
ax.set_ylabel('$V$',font... | tarea1-2/Respuesta.ipynb | ffpenaloza/AstroExp | gpl-3.0 |
Se obtuvo la isócrona de la imagen (línea verde). Al menos pasa cerca de los puntos obtenidos por fotometría.
Sin embargo, para una mejro aproximación sería necesaria una magnitud V mayor, de forma que todo el CMD se mueva a la derecha y hacia abajo.
<hr>
<h2>Pregunta 3</h2>
Para calcular el <em>ridge line</em> del set... | s = 0.22
x = []
y1 = np.arange(16.5,19.4,step=s)
y2 = np.arange(19.5,23.5,step=s)
y = np.append(y1,y2)
for i in y:
a = np.where((i<tbl['V']) & (tbl['V']<i+s) & (tbl['V']-tbl['I']>0.4))
x.append(np.median(tbl['V'][a]-tbl['I'][a]))
fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim(-0.5,1.5)
ax.set_ylim(24,16)
a... | tarea1-2/Respuesta.ipynb | ffpenaloza/AstroExp | gpl-3.0 |
<hr>
<h2>pregunta 4</h2>
Ahora que se tiene la ridge line, se busca una isócrona que se acerque de la mejor manera. Suponiendo que la distancia al cúmulo es el dato mejor conocido, se cambian los valores de edad y metalicidad. Se encuentra que el mejor fit se logra con
<ul>
<li>Edad: 9.89Gyr</li>
<li>Fe/H: -1.55</li>... | fig, ax = plt.subplots(figsize=(10,10))
ax.set_xlim(-0.5,1.5)
ax.set_ylim(24,16)
ax.set_xlabel('$V-I$',fontsize=20)
ax.set_ylabel('$V$',fontsize=20)
ax.plot(tbl['V']-tbl['I']+0.15,tbl['V']+0.15,'k.',alpha=0.4,ms=3)
#nueva isocrona que se acerque a nuestra ridge line
iso = Dartmouth_Isochrone(bands=['V','I'])
model = ... | tarea1-2/Respuesta.ipynb | ffpenaloza/AstroExp | gpl-3.0 |
Set up training data
In the next cell, we set up the training data for this example. We'll be using 100 regularly spaced points on [0,1] which we evaluate the function on and add Gaussian noise to get the training labels.
We'll have two functions - a sine function (y1) and a cosine function (y2).
For MTGPs, our train_t... | train_x = torch.linspace(0, 1, 100)
train_y = torch.stack([
torch.sin(train_x * (2 * math.pi)) + torch.randn(train_x.size()) * 0.2,
torch.cos(train_x * (2 * math.pi)) + torch.randn(train_x.size()) * 0.2,
], -1) | examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.ipynb | jrg365/gpytorch | mit |
Define a multitask model
The model should be somewhat similar to the ExactGP model in the simple regression example.
The differences:
We're going to wrap ConstantMean with a MultitaskMean. This makes sure we have a mean function for each task.
Rather than just using a RBFKernel, we're using that in conjunction with a ... | class MultitaskGPModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood):
super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = gpytorch.means.MultitaskMean(
gpytorch.means.ConstantMean(), num_tasks=2
)
self.covar... | examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.ipynb | jrg365/gpytorch | mit |
Train the model hyperparameters | # this is for running the notebook in our testing framework
import os
smoke_test = ('CI' in os.environ)
training_iterations = 2 if smoke_test else 50
# Find optimal model hyperparameters
model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=0.1) # Includes Gau... | examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.ipynb | jrg365/gpytorch | mit |
Make predictions with the model | # Set into eval mode
model.eval()
likelihood.eval()
# Initialize plots
f, (y1_ax, y2_ax) = plt.subplots(1, 2, figsize=(8, 3))
# Make predictions
with torch.no_grad(), gpytorch.settings.fast_pred_var():
test_x = torch.linspace(0, 1, 51)
predictions = likelihood(model(test_x))
mean = predictions.mean
lo... | examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.ipynb | jrg365/gpytorch | mit |
Plugin setup
We have data from the same time interval from Swift BAT and a GBM NAI and BGO detector. We have preprocessed GBM data to so that it is OGIP compliant. (Remember that we can handle the raw data with the TimeSeriesBuilder). Thus, we will use the OGIPLike plugin to read in each dataset, make energy selections... | bat_pha = get_path_of_data_file("datasets/bat/gbm_bat_joint_BAT.pha")
bat_rsp = get_path_of_data_file("datasets/bat/gbm_bat_joint_BAT.rsp")
bat = OGIPLike("BAT", observation=bat_pha, response=bat_rsp)
bat.set_active_measurements("15-150")
bat.view_count_spectrum() | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Fermi GBM | nai6 = OGIPLike(
"n6",
get_path_of_data_file("datasets/gbm/gbm_bat_joint_NAI_06.pha"),
get_path_of_data_file("datasets/gbm/gbm_bat_joint_NAI_06.bak"),
get_path_of_data_file("datasets/gbm/gbm_bat_joint_NAI_06.rsp"),
spectrum_number=1,
)
nai6.set_active_measurements("8-900")
nai6.view_count_spectrum... | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Model setup
We setup up or spectrum and likelihood model and combine the data. 3ML will automatically assign the proper likelihood to each data set. At first, we will assume a perfect calibration between the different detectors and not a apply a so-called effective area correction. | band = Band()
model_no_eac = Model(PointSource("joint_fit_no_eac", 0, 0, spectral_shape=band)) | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Spectral fitting
Now we simply fit the data by building the data list, creating the joint likelihood and running the fit.
No effective area correction | data_list = DataList(bat, nai6, bgo0)
jl_no_eac = JointLikelihood(model_no_eac, data_list)
jl_no_eac.fit() | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
The fit has resulted in a very typical Band function fit. Let's look in count space at how good of a fit we have obtained. | threeML_config["ogip"]["model plot cmap"] = "Set1"
display_spectrum_model_counts(
jl_no_eac, step=False, min_rate=[0.01, 10.0, 10.0], data_colors=["grey", "k", "k"]
) | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
It seems that the effective areas between GBM and BAT do not agree! We can look at the goodness of fit for the various data sets. | gof_object = GoodnessOfFit(jl_no_eac)
with parallel_computation():
gof, res_frame, lh_frame = gof_object.by_mc(n_iterations=8000)
import pandas as pd
pd.Series(gof) | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Both the GBM NaI detector and Swift BAT exhibit poor GOF.
With effective are correction
Now let's add an effective area correction between the detectors to see if this fixes the problem. The effective area is a nuissance parameter that attempts to model systematic problems in a instruments calibration. It simply scales... | # turn on the effective area correction and set it's bounds
nai6.use_effective_area_correction(0.2, 1.8)
bgo0.use_effective_area_correction(0.2, 1.8)
model_eac = Model(PointSource("joint_fit_eac", 0, 0, spectral_shape=band))
jl_eac = JointLikelihood(model_eac, data_list)
jl_eac.fit() | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Now we have a much better fit to all data sets | display_spectrum_model_counts(
jl_eac, step=False, min_rate=[0.01, 10.0, 10.0], data_colors=["grey", "k", "k"]
)
gof_object = GoodnessOfFit(jl_eac)
with parallel_computation():
gof, res_frame, lh_frame = gof_object.by_mc(
n_iterations=8000, continue_on_failure=True
)
import pandas as pd
pd.Serie... | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Examining the differences
Let's plot the fits in model space and see how different the resulting models are. | plot_spectra(
jl_eac.results,
jl_no_eac.results,
fit_cmap="Set1",
contour_cmap="Set1",
flux_unit="erg2/(keV s cm2)",
equal_tailed=True,
) | docs/examples/joint_BAT_gbm_demo.ipynb | giacomov/3ML | bsd-3-clause |
Load in house sales data
Dataset is from house sales in King County, the region where the city of Seattle, WA is located. | sales = graphlab.SFrame('kc_house_data.gl/')
sales.head() | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Compute RSS
Now that we can make predictions given the model, let's write a function to compute the RSS of the model. Complete the function below to calculate RSS given the model, data, and the outcome. | def get_residual_sum_of_squares(model, data, outcome):
# First get the predictions
predictions = model.predict(data)
# Then compute the residuals/errors
errors = outcome - predictions
# Then square and add them up
RSS = (errors * errors).sum()
return(RSS) | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Next create the following 4 new features as column in both TEST and TRAIN data:
* bedrooms_squared = bedrooms*bedrooms
* bed_bath_rooms = bedrooms*bathrooms
* log_sqft_living = log(sqft_living)
* lat_plus_long = lat + long
As an example here's the first one: | train_data['bedrooms_squared'] = train_data['bedrooms'].apply(lambda x: x**2)
test_data['bedrooms_squared'] = test_data['bedrooms'].apply(lambda x: x**2)
# create the remaining 3 features in both TEST and TRAIN data
train_data['bed_bath_rooms'] = (train_data['bedrooms'] * train_data['bathrooms']).apply(lambda x: x)
te... | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Squaring bedrooms will increase the separation between not many bedrooms (e.g. 1) and lots of bedrooms (e.g. 4) since 1^2 = 1 but 4^2 = 16. Consequently this feature will mostly affect houses with many bedrooms.
bedrooms times bathrooms gives what's called an "interaction" feature. It is large when both of them are lar... | print 'bedrooms_squared:', test_data['bedrooms_squared'].mean()
print 'bed_bath_rooms', test_data['bed_bath_rooms'].mean()
print 'lat_plus_long', test_data['lat_plus_long'].mean()
print 'log_sqft_living', test_data['log_sqft_living'].mean() | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Learning Multiple Models
Now we will learn the weights for three (nested) models for predicting house prices. The first model will have the fewest features the second model will add one more feature and the third will add a few more:
* Model 1: squarefeet, # bedrooms, # bathrooms, latitude & longitude
* Model 2: add be... | model_1_features = ['sqft_living', 'bedrooms', 'bathrooms', 'lat', 'long']
model_2_features = model_1_features + ['bed_bath_rooms']
model_3_features = model_2_features + ['bedrooms_squared', 'log_sqft_living', 'lat_plus_long'] | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Now that you have the features, learn the weights for the three different models for predicting target = 'price' using graphlab.linear_regression.create() and look at the value of the weights/coefficients: | # Learn the three models: (don't forget to set validation_set = None)
model_1 = graphlab.linear_regression.create(train_data, target = 'price',
features = model_1_features, validation_set = None)
model_2 = graphlab.linear_regression.create(train_data, target = 'price',
... | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Quiz Question: What is the sign (positive or negative) for the coefficient/weight for 'bathrooms' in model 1?
Quiz Question: What is the sign (positive or negative) for the coefficient/weight for 'bathrooms' in model 2?
Think about what this means.
Comparing multiple models
Now that you've learned three models and extr... | # Compute the RSS on TRAINING data for each of the three models and record the values:
rss_model_1 = get_residual_sum_of_squares(model_1, train_data, train_data['price'])
rss_model_2 = get_residual_sum_of_squares(model_2, train_data, train_data['price'])
rss_model_3 = get_residual_sum_of_squares(model_3, train_data, tr... | Machine-Learning-Specialization/machine_learning_regression/week2/multiple-regression-assignment-1.ipynb | subhankarb/Machine-Learning-PlayGround | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.