def evaluate(X_train, X_test, y_train, y_test, alpha):
    # Implement your method here
    model = Lasso(alpha=alpha)
    model.fit(X_train,y_train)
    MSEsum = 0
    y_pred = model.predict(X_test)
    for i in range(len(y_test)):
        MSEsum+=(y_pred[i]-y_test[i])**2
    return MSEsum/len(y_test)
Esempio n. 2
0
def run_all(gpu=False, double_precision=False):

    print("\nLasso.")
    print "Solve time:\t{:.2e} seconds\n".format(
        Lasso(200, 2000, gpu=gpu, double_precision=double_precision))

    print("\nLasso Path.")
    print "Solve time:\t{:.2e} seconds\n".format(
        LassoPath(200, 1000, gpu=gpu, double_precision=double_precision))

    print("\nLogistic Regression.")
    print "Solve time:\t{:.2e} seconds\n".format(
        Logistic(1000, 100, gpu=gpu, double_precision=double_precision))

    print("\nLinear Program in Equality Form.")
    print "Solve time:\t{:.2e} seconds\n".format(
        LpEq(1000, 200, gpu=gpu, double_precision=double_precision))

    print("\nLinear Program in Inequality Form.")
    print "Solve time:\t{:.2e} seconds\n".format(
        LpIneq(1000, 200, gpu=gpu, double_precision=double_precision))

    print("\nNon-Negative Least Squares.")
    print "Solve time:\t{:.2e} seconds\n".format(
        NonNegL2(1000, 200, gpu=gpu, double_precision=double_precision))

    print("\nSupport Vector Machine.")
    print "Solve time:\t{:.2e} seconds\n".format(
        Svm(1000, 200, gpu=gpu, double_precision=double_precision))
    def __init__(self, robot, algorithm):
        self.robot = robot 
        self.lasso = Lasso()
        self.algorithm = algorithm
        self.state = algorithm.getInitialState(self.getSensorState())
        self.terminate = False

        self.behaviors = {
            "explore": self.explore,
            "faceObject": self.faceObject,
            "stop": self.stop,
            "identifyMoveableObject": self.identifyMoveableObject,
            "grab": self.grab,
            "release": self.release,
            "tryGrab": self.tryGrab,
        }
Esempio n. 4
0
def deploy_lasso(sample_id):
    sample_data = sample_data_list[sample_id]
    sample_x, sample_y = sample_data.x, sample_data.y
    sample_phi = generate_polynomial_features(sample_x)

    title = 'LASSO'

    log = open(result_sub_path + title + '_' + str(sample_id) + '.txt', 'w')
    img_path = result_sub_path + title + '_' + str(sample_id) + '.png'

    candidate_pred_y, candidate_error, candidate_sample_error, candidate_lambda = [], [], [], []
    _lambda = 0.000001
    _lambda_step = 1.05
    log.write("range of lambda: " + str(_lambda) + ' : ')

    for candidate_id in range(1000):
        model = Lasso()
        model.fit(sample_phi, sample_y, _lambda)

        pred_sample_y = model.predict(sample_phi)
        pred_y = model.predict(gt_phi)

        sample_error = compute_mean_squared_error(pred_sample_y, sample_y)
        error = compute_mean_squared_error(pred_y, gt_y)

        candidate_sample_error.append((sample_error, candidate_id))
        candidate_error.append(error)
        candidate_lambda.append(_lambda)
        candidate_pred_y.append(pred_y)

        _lambda *= _lambda_step

    log.write(str(_lambda) + '\n')
    candidate_error.sort()

    (sample_error, best_id) = candidate_sample_error[0]
    error = candidate_error[best_id]
    pred_y = candidate_pred_y[best_id]
    _lambda = candidate_lambda[best_id]

    log.write("lambda: " + str(_lambda) + '\n')
    log.write("Training MSE: " + str(sample_error) + '\n')
    log.write("Testing MSE: " + str(error) + '\n')


    visualize(sample_x, sample_y, gt_x, gt_y, pred_y, title, img_path)
    return sample_error, error
Esempio n. 5
0
def deploy_lasso():
    title = 'LASSO'
    log = open(result_sub_path + title + '_2.txt', 'w')
    img_path = result_sub_path + title + '_2.png'

    candidate_pred_y, candidate_error, candidate_sample_error, candidate_lambda = [], [], [], []
    _lambda = 1.0
    _lambda_step = 1.05
    log.write("range of lambda: " + str(_lambda) + ' : ')

    for candidate_id in range(10):
        model = Lasso()
        model.fit(sample_phi, sample_y, _lambda)

        pred_sample_y = model.predict(sample_phi)
        pred_y = model.predict(gt_phi)

        sample_error = compute_mean_squared_error(pred_sample_y, sample_y)
        error = compute_mean_squared_error(pred_y, gt_y)

        candidate_sample_error.append((sample_error, candidate_id))
        candidate_error.append(error)
        candidate_lambda.append(_lambda)
        candidate_pred_y.append(pred_y)

        _lambda *= _lambda_step

    log.write(str(_lambda) + '\n')
    candidate_error.sort()

    (sample_error, best_id) = candidate_sample_error[0]
    error = candidate_error[best_id]
    pred_y = candidate_pred_y[best_id]
    _lambda = candidate_lambda[best_id]

    log.write("lambda: " + str(_lambda) + '\n')
    log.write("Training MSE: " + str(sample_error) + '\n')
    log.write("Testing MSE: " + str(error) + '\n')

    sample_error = compute_mean_absolute_error(pred_sample_y, sample_y)
    error = compute_mean_absolute_error(pred_y, gt_y)

    log.write("Training MAE: " + str(sample_error) + '\n')
    log.write("Testing MAE: " + str(error) + '\n')

    visualize_people_counting(gt_y, pred_y, title, img_path)
class Behaviors():

    def __init__(self, robot, algorithm):
        self.robot = robot 
        self.lasso = Lasso()
        self.algorithm = algorithm
        self.state = algorithm.getInitialState(self.getSensorState())
        self.terminate = False

        self.behaviors = {
            "explore": self.explore,
            "faceObject": self.faceObject,
            "stop": self.stop,
            "identifyMoveableObject": self.identifyMoveableObject,
            "grab": self.grab,
            "release": self.release,
            "tryGrab": self.tryGrab,
        }

    def run(self):
        behaviorResult = None
        while not self.terminate:
            self.state = self.algorithm.eventHandler(self.state,
                    self.getSensorState(), behaviorResult)
            behaviorResult = self.behaviors[self.state]()

    def getSensorState(self):
        return {
            "frontSensors": self.robot.getFrontSensors(),
            "groundSensors": self.robot.getGroundSensors(),
            "rearSensors": self.robot.getRearSensors(),
            "accelerometer": self.robot.getAccelerometer(),
            "micIntensity": self.robot.getMicIntensity(),
            "lassoState": self.lasso.getState()
        }

    def safe(self):
        return not self.robot.overEdge()

    def grab(self):
        self.lasso.up()
        self.robot.left(10)
        self.robot.backwards(2)
        while len(filter(lambda x: x > 2500, self.robot.getRearSensors())) > 0:
            self.robot.forward(0.1)
        self.lasso.down()

    def tryGrab(self):
        self.grab()
        self.robot.forward(5)
        time.sleep(1.5)
        if len(filter(lambda x: x > 1000, self.robot.getRearSensors())) == 0:
            self.release()
            return
        
        before_sensors = self.robot.getRearSensors()
        self.robot.forward(1)
        time.sleep(0.5)
        after_sensors = self.robot.getRearSensors()
        if len(filter(lambda (x,y): abs(x-y) > 100, zip(before_sensors, after_sensors))) == 0:
            self.release()
            return

        self.robot.left(5)
        if len(filter(lambda x: x > 1000, self.robot.getRearSensors())) == 0:
            self.release()
Esempio n. 7
0
#! -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from sklearn import cross_validation
from lasso import Lasso

df = pd.read_csv("Boston.csv", index_col=0)
y = df.iloc[:, 13].values
df = (df - df.mean()) / df.std()  # 基準化
X = df.iloc[:, :13].values

model = Lasso(alpha=1.0, max_iter=1000)
model.fit(X, y)

print(model.intercept_)
print(model.coef_)

scores = cross_validation.cross_val_score(model,
                                          X,
                                          y,
                                          cv=5,
                                          scoring='mean_squared_error')
print(np.mean(scores))
Esempio n. 8
0
#! -*- coding: utf-8 -*-

import pandas as pd
import numpy as np
from sklearn import cross_validation
from lasso import Lasso

df = pd.read_csv("Boston.csv", index_col=0)
y = df.iloc[:,  13].values
df = (df - df.mean())/df.std() # 基準化
X = df.iloc[:, :13].values

model = Lasso(alpha=1.0, max_iter=1000)
model.fit(X, y)

print model.intercept_
print model.coef_

scores = cross_validation.cross_val_score(model, X, y, cv=5, scoring='mean_squared_error')
print np.mean(scores)