In [1]:
%matplotlib inline
In [2]:
import numpy as np
import pandas as pd
# 統計用ツール
import statsmodels.api as sm
import statsmodels.tsa.api as tsa
from patsy import dmatrices
# 自作の空間統計用ツール
from spatialstat import *
#描画
import matplotlib.pyplot as plt
from pandas.tools.plotting import autocorrelation_plot
import seaborn as sns
sns.set(font=['IPAmincho'])
#深層学習
import chainer
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
import pyper
In [3]:
data = pd.read_csv("TokyoSingle.csv")
data = data.dropna()
CITY_NAME = data['CITY_CODE'].copy()
In [4]:
CITY_NAME[CITY_NAME == 13101] = '01千代田区'
CITY_NAME[CITY_NAME == 13102] = "02中央区"
CITY_NAME[CITY_NAME == 13103] = "03港区"
CITY_NAME[CITY_NAME == 13104] = "04新宿区"
CITY_NAME[CITY_NAME == 13105] = "05文京区"
CITY_NAME[CITY_NAME == 13106] = "06台東区"
CITY_NAME[CITY_NAME == 13107] = "07墨田区"
CITY_NAME[CITY_NAME == 13108] = "08江東区"
CITY_NAME[CITY_NAME == 13109] = "09品川区"
CITY_NAME[CITY_NAME == 13110] = "10目黒区"
CITY_NAME[CITY_NAME == 13111] = "11大田区"
CITY_NAME[CITY_NAME == 13112] = "12世田谷区"
CITY_NAME[CITY_NAME == 13113] = "13渋谷区"
CITY_NAME[CITY_NAME == 13114] = "14中野区"
CITY_NAME[CITY_NAME == 13115] = "15杉並区"
CITY_NAME[CITY_NAME == 13116] = "16豊島区"
CITY_NAME[CITY_NAME == 13117] = "17北区"
CITY_NAME[CITY_NAME == 13118] = "18荒川区"
CITY_NAME[CITY_NAME == 13119] = "19板橋区"
CITY_NAME[CITY_NAME == 13120] = "20練馬区"
CITY_NAME[CITY_NAME == 13121] = "21足立区"
CITY_NAME[CITY_NAME == 13122] = "22葛飾区"
CITY_NAME[CITY_NAME == 13123] = "23江戸川区"
In [5]:
#Make Japanese Block name
BLOCK = data["CITY_CODE"].copy()
BLOCK[BLOCK == 13101] = "01都心・城南"
BLOCK[BLOCK == 13102] = "01都心・城南"
BLOCK[BLOCK == 13103] = "01都心・城南"
BLOCK[BLOCK == 13104] = "01都心・城南"
BLOCK[BLOCK == 13109] = "01都心・城南"
BLOCK[BLOCK == 13110] = "01都心・城南"
BLOCK[BLOCK == 13111] = "01都心・城南"
BLOCK[BLOCK == 13112] = "01都心・城南"
BLOCK[BLOCK == 13113] = "01都心・城南"
BLOCK[BLOCK == 13114] = "02城西・城北"
BLOCK[BLOCK == 13115] = "02城西・城北"
BLOCK[BLOCK == 13105] = "02城西・城北"
BLOCK[BLOCK == 13106] = "02城西・城北"
BLOCK[BLOCK == 13116] = "02城西・城北"
BLOCK[BLOCK == 13117] = "02城西・城北"
BLOCK[BLOCK == 13119] = "02城西・城北"
BLOCK[BLOCK == 13120] = "02城西・城北"
BLOCK[BLOCK == 13107] = "03城東"
BLOCK[BLOCK == 13108] = "03城東"
BLOCK[BLOCK == 13118] = "03城東"
BLOCK[BLOCK == 13121] = "03城東"
BLOCK[BLOCK == 13122] = "03城東"
BLOCK[BLOCK == 13123] = "03城東"
In [6]:
names = list(data.columns) + ['CITY_NAME', 'BLOCK']
data = pd.concat((data, CITY_NAME, BLOCK), axis = 1)
data.columns = names
CENSUS: 市区町村コード(9桁)
P: 成約価格
S: 専有面積
L: 土地面積
R: 部屋数
RW: 前面道路幅員
CY: 建築年
A: 建築後年数(成約時)
TS: 最寄駅までの距離
TT: 東京駅までの時間
ACC: ターミナル駅までの時間
WOOD: 木造ダミー
SOUTH: 南向きダミー
RSD: 住居系地域ダミー
CMD: 商業系地域ダミー
IDD: 工業系地域ダミー
FAR: 建ぺい率
FLR: 容積率
TDQ: 成約時点(四半期)
X: 緯度
Y: 経度
CITY_CODE: 市区町村コード(5桁)
CITY_NAME: 市区町村名
BLOCK: 地域ブロック名
In [7]:
print(data['CITY_NAME'].value_counts())
In [8]:
print(data.pivot_table(index=['TDQ'], columns=['CITY_NAME']))
In [9]:
print(data.pivot_table(index=['TDQ'], columns=['BLOCK']))
In [10]:
data['P'].hist()
Out[10]:
In [11]:
(np.log(data['P'])).hist()
Out[11]:
In [12]:
data['A'].hist()
Out[12]:
In [13]:
plt.figure(figsize=(20,8))
plt.subplot(4, 2, 1)
data['P'].hist()
plt.title(u"成約価格")
plt.subplot(4, 2, 2)
data['S'].hist()
plt.title("専有面積")
plt.subplot(4, 2, 3)
data['L'].hist()
plt.title("土地面積")
plt.subplot(4, 2, 4)
data['R'].hist()
plt.title("部屋数")
plt.subplot(4, 2, 5)
data['A'].hist()
plt.title("建築後年数")
plt.subplot(4, 2, 6)
data['RW'].hist()
plt.title("前面道路幅員")
plt.subplot(4, 2, 7)
data['TS'].hist()
plt.title("最寄駅までの距離")
plt.subplot(4, 2, 8)
data['TT'].hist()
plt.title(u"東京駅までの時間")
Out[13]:
In [14]:
plt.figure(figsize=(20,8))
data['TDQ'].value_counts().plot(kind='bar')
Out[14]:
In [15]:
plt.figure(figsize=(20,8))
data['CITY_NAME'].value_counts().plot(kind='bar') #市区町村別の件数
Out[15]:
In [16]:
vars = ['P', 'S', 'L', 'R', 'RW', 'A', 'TS', 'TT', 'WOOD', 'SOUTH', 'CMD', 'IDD', 'FAR', 'X', 'Y']
eq = fml_build(vars)
y, X = dmatrices(eq, data=data, return_type='dataframe')
CITY_NAME = pd.get_dummies(data['CITY_NAME'])
TDQ = pd.get_dummies(data['TDQ'])
X = pd.concat((X, CITY_NAME, TDQ), axis=1)
datas = pd.concat((y, X), axis=1)
datas = datas[datas['12世田谷区'] == 1][0:5000]
In [17]:
datas.head()
Out[17]:
In [18]:
vars = ['S', 'L', 'R', 'RW', 'A', 'TS', 'TT', 'WOOD', 'SOUTH', 'CMD', 'IDD', 'FAR']
#vars += vars + list(TDQ.columns)
In [76]:
class CAR(Chain):
def __init__(self, unit1, unit2, unit3, col_num):
self.unit1 = unit1
self.unit2 = unit2
self.unit3 = unit3
super(CAR, self).__init__(
l1 = L.Linear(col_num, unit1),
l2 = L.Linear(self.unit1, self.unit1),
l3 = L.Linear(self.unit1, self.unit2),
l4 = L.Linear(self.unit2, self.unit3),
l5 = L.Linear(self.unit3, self.unit3),
l6 = L.Linear(self.unit3, 1),
)
def __call__(self, x, y):
fv = self.fwd(x, y)
loss = F.mean_squared_error(fv, y)
return loss
def fwd(self, x, y):
h1 = F.sigmoid(self.l1(x))
h2 = F.sigmoid(self.l2(h1))
h3 = F.sigmoid(self.l3(h2))
h4 = F.sigmoid(self.l4(h3))
h5 = F.sigmoid(self.l5(h4))
h6 = self.l6(h5)
return h6
In [204]:
from scipy import optimize
In [380]:
-1/0.54
Out[380]:
In [466]:
class OLS_DL_ARmodel(object):
def __init__(self, data, vars, bs=200, n=1000):
self.vars = vars
eq = fml_build(vars)
y, X = dmatrices(eq, data=datas, return_type='dataframe')
self.n = n
self.y_in = y[:-n]
self.X_in = X[:-n]
self.y_ex = y[-n:]
self.X_ex = X[-n:]
self.logy_in = np.log(self.y_in)
self.logy_ex = np.log(self.y_ex)
self.bs = bs
self.ido_in = np.array([datas['X'][:-n]])
self.keido_in = np.array([datas['Y'][:-n]])
self.W_in = ((self.ido_in.T - self.ido_in)**2 +
(self.keido_in.T - self.keido_in)**2)
N = np.array(np.matrix(self.W_in)*np.matrix(np.ones(len(self.ido_in[0]))).T)
self.W_in = self.W_in/N
self.ido_ex = np.array([datas['X'][-n:]])
self.keido_ex = np.array([datas['Y'][-n:]])
#la, v = np.linalg.eig(model.W_in)
#self.minl = min(la)
#self.maxl = max(la)
def loglf(self, lbda):
self.IW = np.identity(len(self.ido_in[0])) - lbda*self.W_in
A = np.matrix(self.IW)*np.matrix(self.u)
L = np.array(np.log(np.linalg.det(self.IW)) - A.T*A/(2*self.sigma))[0][0]
return -L
def Main(self, ite=100, bs=200, add=False):
model = sm.OLS(self.logy_in, self.X_in, intercept=False)
self.reg = model.fit()
y_in_mat = np.matrix(np.array(self.y_in, dtype='float32'))
X_in_mat = np.matrix(np.array(self.X_in, dtype='float32'))
params = np.matrix(np.array([self.reg.params]))
resid = np.array(y_in_mat.T - params*X_in_mat.T, dtype='float32')[0]
resid = resid.reshape(len(resid),1)
X_in = np.array(self.X_in, dtype='float32')
yall = Variable(resid)
xall = Variable(X_in)
num, col_num = X_in.shape
self.sigma = 10
if add is False:
self.model1 = CAR(10, 10, 3, col_num)
optimizer = optimizers.Adam()
optimizer.setup(self.model1)
self.lbda = 0
for k in range(5):
for j in range(ite):
sffindx = np.random.permutation(num)
for i in range(0, num, bs):
x = Variable(X_in[sffindx[i:(i+bs) if (i+bs) < num else num]])
y = Variable(resid[sffindx[i:(i+bs) if (i+bs) < num else num]])
self.model1.zerograds()
loss = self.model1(x, y)
loss.backward()
optimizer.update()
loss_val = loss.data
print('epoch:', k)
print('train mean loss={}'.format(loss_val))
print('lambda:',self.lbda)
print(' - - - - - - - - - ')
self.u = resid - self.model1.fwd(xall, yall).data
self.lbda = optimize.fminbound(self.loglf, -1/0.54, 0.999, maxfun=1000)
IW = np.identity(len(self.ido_in[0])) - self.lbda*self.W_in
self.IW = np.matrix(IW)
omega_inv = IW.T*IW
gls_model = sm.GLS(self.logy_in - self.model1.fwd(xall, yall).data, self.X_in, sigma=omega_inv)
gls_results = gls_model.fit()
params = np.matrix(np.array([gls_results.params]))
resid = np.array(y_in_mat.T - params*X_in_mat.T, dtype='float32')[0]
resid = resid.reshape(len(resid),1)
self.sigma = (np.matrix(self.u).T*omega_inv*np.matrix(self.u))/self.n
def predict(self):
y_ex = np.array(self.y_ex, dtype='float32').reshape(len(self.y_ex))
X_ex = np.array(self.X_ex, dtype='float32')
X_ex = Variable(X_ex)
resid_pred = self.model1.fwd(X_ex, X_ex).data
print(resid_pred[:10])
self.logy_pred = np.matrix(self.X_ex)*np.matrix(self.reg.params).T
self.error1 = np.array(y_ex - np.exp(self.logy_pred.reshape(len(self.logy_pred),)))[0]
self.pred = np.exp(self.logy_pred) + resid_pred
self.error2 = np.array(y_ex - self.pred.reshape(len(self.pred),))[0]
def compare(self):
plt.hist(self.error1)
plt.hist(self.error2)
In [467]:
vars = ['P', 'S', 'L', 'R', 'RW', 'A', 'TS', 'TT', 'WOOD', 'SOUTH', 'CMD', 'IDD', 'FAR', 'X', 'Y']
#vars += vars + list(TDQ.columns)
In [468]:
model = OLS_DL_ARmodel(datas, vars)
In [469]:
model.Main(ite=5000, bs=200)
In [291]:
model.DL(ite=200, bs=200, add=True)
In [320]:
model.DL(ite=10000, bs=200, add=True)
In [ ]:
i = 1
In [ ]:
ido = np.append(model.ido_in, model.ido_ex[i])
keido = np.append(model.keido_in, model.keido_ex[i])
w = ((ido.T - ido)**2 + (keido.T - keido)**2)[-1]
In [ ]:
N = sum(w)
w = w/N
error2[i] = error2[i] - lbda*w*np.append(error1, error2[i])
In [471]:
model.predict()
青がOLSの誤差、緑がOLSと深層学習を組み合わせた誤差。
In [470]:
model.compare()
In [457]:
print(np.mean(model.error1))
print(np.mean(model.error2))
In [458]:
print(np.mean(np.abs(model.error1)))
print(np.mean(np.abs(model.error2)))
In [459]:
print(max(np.abs(model.error1)))
print(max(np.abs(model.error2)))
In [460]:
print(np.var(model.error1))
print(np.var(model.error2))
In [316]:
fig = plt.figure()
ax = fig.add_subplot(111)
errors = [model.error1, model.error2]
bp = ax.boxplot(errors)
plt.grid()
plt.ylim([-5000,5000])
plt.title('分布の箱ひげ図')
plt.show()
In [415]:
X = model.X_ex['X'].values
Y = model.X_ex['Y'].values
In [318]:
e = model.error2
In [319]:
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D
fig=plt.figure()
ax=Axes3D(fig)
ax.scatter3D(X, Y, e)
plt.show()
In [331]:
t
Out[331]:
In [358]:
plt.hist(Xs)
Out[358]:
In [339]:
import numpy as np
from scipy.stats import gaussian_kde
import matplotlib.pyplot as plt
In [564]:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
X = model.X_ex['X'].values
Y = model.X_ex['Y'].values
Xs = np.linspace(min(X),max(X),10)
Ys = np.linspace(min(Y),max(Y),10)
error = model.error1
Xgrid, Ygrid = np.meshgrid(Xs, Ys)
Z = LL(X, Y, Xs, Ys, error)
fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(Xgrid,Ygrid,Z) #<---ここでplot
plt.show()
In [505]:
fig = plt.figure()
ax = Axes3D(fig)
ax.set_zlim(-100, 500)
ax.plot_surface(Xgrid,Ygrid,Z) #<---ここでplot
plt.show()
In [541]:
h = 10
(0.9375*(1-((X-1)/h)**2)**2)*(0.9375*(1-((Y-2)/h)**2)**2)
Out[541]:
In [562]:
def LL(X, Y, Xs, Ys, error):
n = len(X)
h = 0.1
error = model.error2
mean_of_error = np.zeros((len(Xs), len(Ys)))
for i in range(len(Xs)):
for j in range(len(Ys)):
u1 = ((X-Xs[i])/h)**2
u2 = ((Y-Ys[j])/h)**2
k = (0.9375*(1-((X-Xs[i])/h)**2)**2)*(0.9375*(1-((Y-Ys[j])/h)**2)**2)
K = np.diag(k)
indep = np.matrix(np.array([np.ones(n), X - Xs[i], Y-Ys[j]]).T)
dep = np.matrix(np.array([error]).T)
gls_model = sm.GLS(dep, indep, sigma=K)
gls_results = gls_model.fit()
mean_of_error[i, j] = gls_results.params[0]
return mean_of_error
In [558]:
h = 200
u1 = ((X-30)/h)**2
In [559]:
u1
Out[559]:
In [557]:
u1[u1 < 0] = 0
In [467]:
for x in range(lXs[:2]):
print(x)
In [499]:
mean_of_error
Out[499]:
In [468]:
Out[468]:
In [367]:
plt.plot(gaussian_kde(Y, 0.1)(Ys))
Out[367]:
In [ ]:
N = 5
means = np.random.randn(N,2) * 10 + np.array([100, 200])
stdev = np.random.randn(N,2) * 10 + 30
count = np.int64(np.int64(np.random.randn(N,2) * 10000 + 50000))
a = [
np.hstack([
np.random.randn(count[i,j]) * stdev[i,j] + means[i,j]
for j in range(2)])
for i in range(N)]
In [337]:
for x in Xs:
for y in Ys:
Out[337]:
In [249]:
def loclinearc(points,x,y,h):
n = len(points[,1])
const = matrix(1, nrow=length(x), ncol=1)
bhat = matrix(0, nrow=3, ncol=n)
b1 = matrix(0, n, n)
predict = matrix(0, n, 1)
for (j in 1:n) {
for (i in 1:n) {
a <- -.5*sign( abs( (points[i, 1]*const - x[,1])/h ) -1 ) + .5
#get the right data points, (K(x) ~=0)
b <- -.5*sign( abs( (points[j, 2]*const - x[,2])/h ) -1 ) + .5
x1andy <- nonzmat(cbind((x[,1]*a*b), (y*a*b)))
x2andy <- nonzmat(cbind((x[,2]*a*b), (y*a*b)))
ztheta1 <- x1andy[,1]
ztheta2 <- x2andy[,1]
yuse <- x1andy[,2]
q1 <- (ztheta1 - points[i,1]);
q2 <- (ztheta2 - points[j,2]);
nt1 <- ( (ztheta1- points[i,1])/h )
nt2 <- ( (ztheta2- points[j,2])/h )
#q2 = ((ztheta - points(i,1)).^2)/2;
weights <- diag(c((15/16)%*%( 1-(nt1^2))^2*((15/16)%*%( 1-(nt2^2))^2)))
#Biweight Kernel
tempp3 <- cbind(matrix(1, nrow=length(ztheta1), ncol=1), q1, q2)
bhat[,i] <- solve(t(tempp3)%*%weights%*%tempp3)%*%t(tempp3)%*%weights%*%yuse
}
b1[,j] <- t(bhat[1,])
}
return(b1)
}
Out[249]:
In [ ]:
nonzmat(x):
#This function computes nonzeros of a MATRIX when certain ROWS of the
#matrix are zero. This function returns a matrix with the
#zero rows deleted
m, k = x.shape
xtemp = matrix(np.zeros(m, k))
for (i in 1:m) {
xtemp[i,] <- ifelse(x[i,] == matrix(0, nrow=1, ncol=k), 99999*matrix(1, nrow=1, ncol=k), x[i,])
}
xtemp <- xtemp - 99999
if (length(which(xtemp !=0,arr.ind = T)) == 0) {
a <- matrix(-99999, nrow=1, ncol=k)
} else {
a <- xtemp[which(xtemp !=0,arr.ind = T)]
}
a <- a + 99999
n1 <- length(a)
rowlen <- n1/k
collen <- k
out = matrix(a, nrow=rowlen, ncol=collen)
return(out)
}
In [265]:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.tri as mtri
#============
# First plot
#============
# Plot the surface. The triangles in parameter space determine which x, y, z
# points are connected by an edge.
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_trisurf(X, Y, e)
ax.set_zlim(-1, 1)
plt.show()
In [ ]: