波士顿房产预测问题:
from keras.layers import Dense
from keras.datasets import boston_housing
from keras import models,layers
import numpy as np
(train_data,train_target),(test_data,test_target) = boston_housing.load_data()
mean = train_data.mean(axis=0) #求均方误差
train_data -= mean
std = train_data.std(axis=0)
train_data = train_data/std
test_data -= mean
test_data /= std
def build_model(): #建立模型
model = models.Sequential()
model.add(Dense(64,activation='relu',input_shape=(train_data.shape[1],)))
model.add(Dense(64,activation='relu'))
model.add(Dense(1))
model.compile(optimizer='rmsprop',loss='mse',metrics=['mae'])
return model
k = 4 #K折交叉验证
num_val_sample = len(train_data)//k #分成几份
num_epochs = 100
all_scores = []
for i in range(k):
val_data = train_data[i*num_val_sample:(i+1)*num_val_sample] #第k份
val_targets = train_target[i*num_val_sample:(i+1)*num_val_sample]
partial_train_data = np.concatenate([train_data[:i*num_val_sample],train_data[(i+1)*num_val_sample:]],axis=0) #其它拼接
partial_train_target = np.concatenate([train_target[:i*num_val_sample],train_target[(i+1)*num_val_sample:]],axis=0)
model = build_model()
history = model.fit(partial_train_data,partial_train_target,epochs=num_epochs,batch_size=1) #verbose 静默状态
val_mse,val_mae = model.evaluate(val_data,val_targets)
all_scores.append(val_mae)
print(np.mean(all_scores))