RBFNN训练
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import eva
import datetime
start = datetime.datetime.now()
def tanh(x):
return (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
def de_tanh(x):
return (1-x**2)
samnum = 62
hiddenunitnum = 8
indim = 4
outdim = 1
maxepochs = 100
errorfinal = 0.65*10**(-3)
learnrate = 0.0001
df = pd.read_csv("./data/Cr1.csv")
df.columns = ["x", "y", "high", "use", "Cr"]
longtitude = df["x"]
longtitude = np.array(longtitude)
latitude = df["y"]
latitude = np.array(latitude)
elevation = df["high"]
elevation =np.array(elevation)
functional = df["use"]
functional = np.array(functional)
ag=df["Cr"]
ag=np.array(ag)
samplein = np.mat([longtitude,latitude,elevation,functional])
sampleinminmax = np.array([samplein.min(axis=1).T.tolist()[0],samplein.max(axis=1).T.tolist()[0]]).transpose()
sampleout = np.mat([ag])
sampleoutminmax = np.array([sampleout.min(axis=1).T.tolist()[0],sampleout.max(axis=1).T.tolist()[0]]).transpose()
sampleinnorm = ((np.array(samplein.T)-sampleinminmax.transpose()[0])/(sampleinminmax.transpose()[1]-sampleinminmax.transpose()[0])).transpose()
sampleoutnorm = ((np.array(sampleout.T)-sampleoutminmax.transpose()[0])/(sampleoutminmax.transpose()[1]-sampleoutminmax.transpose()[0])).transpose()
sampleinmax = np.array([sampleinnorm.max(axis=1).T.tolist()]).transpose()
sampleinmin = np.array([sampleinnorm.min(axis=1).T.tolist()]).transpose()
sampleoutmax = np.array([sampleoutnorm.max(axis=1).T.tolist()]).transpose()
sampleoutmin = np.array([sampleoutnorm.min(axis=1).T.tolist()]).transpose()
noise = 0.03*np.random.rand(sampleoutnorm.shape[0],sampleoutnorm.shape[1])
sampleoutnorm += noise
x = sampleinnorm.transpose()
estimator=KMeans(n_clusters=8,max_iter=10000)
estimator.fit(x)
w1 = estimator.cluster_centers_
b1 = np.mat(np.zeros((hiddenunitnum,outdim)))
for i in range(hiddenunitnum):
cmax = 0
for j in range(hiddenunitnum):
temp_dist=np.sqrt(np.sum(np.square(w1[i,:]-w1[j,:])))
if cmax<temp_dist:
cmax=temp_dist
b1[i] = cmax/np.sqrt(2*hiddenunitnum)
scale = np.sqrt(3/((indim+outdim)*0.5))
w2 = np.random.uniform(low=-scale,high=scale,size=[hiddenunitnum,outdim])
b2 = np.random.uniform(low=-scale, high=scale, size=[outdim,1])
inputin=np.mat(sampleinnorm.T)
w1=np.mat(w1)
b1=np.mat(b1)
w2=np.mat(w2)
b2=np.mat(b2)
errhistory = np.mat(np.zeros((1,maxepochs)))
for i in range(maxepochs):
hidden_out = np.mat(np.zeros((samnum,hiddenunitnum)))
for a in range(samnum):
for j in range(hiddenunitnum):
d=(inputin[a, :] - w1[j, :]) * (inputin[a, :] - w1[j, :]).T
c=2 * b1[j, :] * b1[j, :]
hidden_out[a, j] = np.exp((-1.0 )* (d/c))
output = tanh(hidden_out * w2 + b2)
out_real = np.mat(sampleoutnorm.transpose())
err = out_real - output
loss = np.sum(np.square(err))
if loss < errorfinal:
break
errhistory[:,i] = loss
output=np.array(output.T)
belta=de_tanh(output).transpose()
dw1now = np.zeros((8,4))
db1now = np.zeros((8,1))
dw2now = np.zeros((8,1))
db2now = np.zeros((1,1))
for j in range(hiddenunitnum):
sum1 = 0.0
sum2 = 0.0
sum3 = 0.0
sum4 = 0.0
for a in range(samnum):
sum1 +=err[a,:] * belta[a,:] * hidden_out[a,j] * (inputin[a,:]-w1[j,:])
sum2 +=err[a,:] * belta[a,:] * hidden_out[a,j] * (inputin[a,:]-w1[j,:])*(inputin[a,:]-w1[j,:]).T
sum3 +=err[a,:] * belta[a,:] * hidden_out[a,j]
sum4 +=err[a,:] * belta[a,:]
dw1now[j,:]=(w2[j,:]/(b1[j,:]*b1[j,:])) * sum1
db1now[j,:] =(w2[j,:]/(b1[j,:]*b1[j,:]*b1[j,:])) * sum2
dw2now[j,:] =sum3
db2now = sum4
w1 += learnrate * dw1now
b1 += learnrate * db1now
w2 += learnrate * dw2now
b2 += learnrate * db2now
print("the iteration is:",i+1,",the loss is:",loss)
print('更新的权重w1:',w1)
print('更新的偏置b1:',b1)
print('更新的权重w2:',w2)
print('更新的偏置b2:',b2)
print("The loss after iteration is :",loss)
np.save("RBFNN_w1.npy",w1)
np.save("RBFNN_b1.npy",b1)
np.save("RBFNN_w2.npy",w2)
np.save("RBFNN_b2.npy",b2)
np.save("RBFNN_rbf_err.npy",errhistory)
diff = sampleoutminmax[:,1]-sampleoutminmax[:,0]
predict_train = (output+1)/2
predict_train = predict_train*diff+sampleoutminmax[0][0]
predict_train = predict_train.flatten()
np.savetxt('./result/RBFNN/predict_train.csv', predict_train, delimiter = ',')
err_train = ag - predict_train
np.savetxt('./result/RBFNN/err_train.csv', err_train, delimiter = ',')
rmse, mae, mape = eva.err(ag, predict_train)
error_train = np.zeros(3)
error_train[0] = rmse
error_train[1] = mae
error_train[2] = mape
print("error:",error_train)
np.savetxt('./result/RBFNN/error_train.csv', error_train, delimiter = ',')
end = datetime.datetime.now()
time = end - start
print("运行时间总计:",time)
RBFNN预测数据(回归)
import numpy as np
import pandas as pd
import datetime
import eva
start = datetime.datetime.now()
def tanh(x):
return (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
def de_tanh(x):
return (1-x**2)
testnum = 20
hiddenunitnum = 8
df = pd.read_csv("./data/Cr2.csv")
df.columns = ["x", "y", "high", "use", "Cr"]
longtitude = df["x"]
longtitude = np.array(longtitude)
latitude = df["y"]
latitude = np.array(latitude)
elevation = df["high"]
elevation =np.array(elevation)
functional = df["use"]
functional = np.array(functional)
As=df["Cr"]
As=np.array(As)
ag=As
samplein = np.mat([longtitude,latitude,elevation,functional])
sampleinminmax = np.array([samplein.min(axis=1).T.tolist()[0],
samplein.max(axis=1).T.tolist()[0]]).transpose()
sampleout = np.mat([ag])
sampleoutminmax = np.array([sampleout.min(axis=1).T.tolist()[0],
sampleout.max(axis=1).T.tolist()[0]]).transpose()
sampleinnorm = (2*(np.array(samplein.T)-sampleinminmax.transpose()[0])
/(sampleinminmax.transpose()[1]-sampleinminmax.transpose()[0])-1).transpose()
sampleoutnorm = (2*(np.array(sampleout.T)-sampleoutminmax.transpose()[0])
/(sampleoutminmax.transpose()[1]-sampleoutminmax.transpose()[0])-1).transpose()
noise = 0.03 * np.random.rand(sampleoutnorm.shape[0],sampleoutnorm.shape[1])
sampleoutnorm += noise
w1=np.load('w1.npy')
w2=np.load('w2.npy')
b1=np.load('b1.npy')
b2=np.load('b2.npy')
w1 = np.mat(w1)
w2 = np.mat(w2)
b1 = np.mat(b1)
b2 = np.mat(b2)
df = pd.read_csv("./data/Cr1.csv")
df.columns = ["x", "y", "high", "use", "Cr"]
longtitude = df["x"]
longtitude = np.array(longtitude)
latitude = df["y"]
latitude = np.array(latitude)
elevation = df["high"]
elevation =np.array(elevation)
functional = df["use"]
functional = np.array(functional)
As=df["Cr"]
As=np.array(As)
input=np.mat([longtitude,latitude,elevation,functional])
inputnorm=(np.array(input.T)-sampleinminmax.transpose()[0])/(sampleinminmax.transpose()[1]-sampleinminmax.transpose()[0])
hidden_out2 = np.mat(np.zeros((testnum,hiddenunitnum)))
for a in range(testnum):
for j in range(hiddenunitnum):
d = (inputnorm[a, :] - w1[j, :]) * (inputnorm[a, :] - w1[j, :]).T
c = 2 * b1[j, :] * b1[j, :].T
hidden_out2[a, j] = np.exp((-1.0) * (d / c))
output = tanh(hidden_out2 * w2 + b2)
diff = sampleoutminmax[:,1]-sampleoutminmax[:,0]
networkout2 = output*diff+sampleoutminmax[0][0]
networkout2 = np.array(networkout2).transpose()
output1=networkout2.flatten()
output1=output1.tolist()
np.savetxt('./result/RBFNN/predict_test.csv', output1, delimiter = ',')
err_test = ag - output1
np.savetxt('./result/RBFNN/err_test.csv', err_test, delimiter = ',')
rmse, mae, mape = eva.err(ag, output1)
print("mape:",mape)
error_train = np.zeros(3)
error_train[0] = rmse
error_train[1] = mae
error_train[2] = mape
np.savetxt('./result/RBFNN/error_test.csv', error_train, delimiter = ',')
for i in range(testnum):
output1[i] = float('%.2f'%output1[i])
end = datetime.datetime.now()
time = end - start
print("运行时间总计:",time)
print("the prediction is:",output1)