Demo entry 2913381

quantile regression

   

Submitted by anonymous on Nov 02, 2015 at 00:57
Language: Python. Code size: 1.4 kB.

import numpy as np
from cvxopt import matrix, solvers
import scipy.io
from matplotlib import pyplot as plt
def quant_reg(XTrain, yTrain, tau = 0.5):
    N = yTrain.shape[0]
    c_arr = np.hstack((np.zeros(1), tau * np.ones(N), (1 - tau) * np.ones(N))).reshape((2 * N + 1, -1))
    A_arr = np.hstack((XTrain.reshape(N, 1), np.identity(N), - np.identity(N)))
    b_arr = yTrain.astype(np.float64).reshape((N, 1))
    G_arr = np.vstack((np.hstack((np.zeros((N, 1)), - np.identity(N), np.zeros((N, N)))), np.hstack((np.zeros((N, 1)), np.zeros((N, N)), - np.identity(N)))))
    h_arr = np.zeros(2 * N)
    c = matrix(c_arr)
    A = matrix(A_arr)
    b = matrix(b_arr)
    G = matrix(G_arr)
    h = matrix(h_arr)
    return np.asarray(solvers.lp(c=c, G=G, h=h, A=A, b=b)['x'])


mat = scipy.io.loadmat('./quantile_matlab.mat')
XTrain = mat['XTrain']
yTrain =  mat['yTrain']

reg_w_25 = quant_reg(XTrain, yTrain, tau = 0.25)
reg_w_50 = quant_reg(XTrain, yTrain, tau = 0.50)
reg_w_75 = quant_reg(XTrain, yTrain, tau = 0.75)
plt.scatter(XTrain, yTrain)
plt.plot(XTrain, XTrain * reg_w_25[0], label = '0.25')
plt.plot(XTrain, XTrain * reg_w_50[0], label = '0.50')
plt.plot(XTrain, XTrain * reg_w_75[0], label = '0.75')
print ('beta25 = ', reg_w_25[0])
print ('beta50 = ', reg_w_50[0])
print ('beta75 = ', reg_w_75[0])
plt.legend()
# plt.show()
plt.savefig('../Figures/Q1.6.pdf', transparent = True)

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).