# 深度学习：利用神经网络在少量数据情况下预测房价走势

```from keras.datasets import boston_housing
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()```

```print(train_data.shape)
print(test_data.shape)```

```mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis = 0)
train_data /= std

test_data -= mean
test_data /= std```

```from keras import models
from keras import layers

def build_model():
'''
由于后面我们需要反复构造同一种结构的网络，所以我们把网络的构造代码放在一个函数中，
后面只要直接调用该函数就可以将网络迅速初始化
'''
model = models.Sequential()
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model```

```import numpy as np
k = 4
num_val_samples = len(train_data) // k #整数除法
num_epochs = 10
all_scores = []
for i in range(k):
print('processing fold #', i)
#依次把k分数据中的每一份作为校验数据集
val_data = train_data[i * num_val_samples : (i+1) * num_val_samples]
val_targets = train_targets[i* num_val_samples : (i+1) * num_val_samples]

#把剩下的k-1分数据作为训练数据,如果第i分数据作为校验数据，那么把前i-1份和第i份之后的数据连起来
partial_train_data = np.concatenate([train_data[: i * num_val_samples],
train_data[(i+1) * num_val_samples:]], axis = 0)
partial_train_targets = np.concatenate([train_targets[: i * num_val_samples],
train_targets[(i+1) * num_val_samples: ]],
axis = 0)
print("build model")
model = build_model()
#把分割好的训练数据和校验数据输入网络
model.fit(partial_train_data, partial_train_targets, epochs = num_epochs,
batch_size = 1, verbose = 0)
print("evaluate the model")
val_mse, val_mae = model.evaluate(val_data, val_targets, verbose = 0)
all_scores.append(val_mae)

print(all_scores)```

```import numpy as np
k = 4
num_val_samples = len(train_data) // k #整数除法
num_epochs = 200
all_mae_histories = []

for i in range(k):
print('processing fold #', i)
#依次把k分数据中的每一份作为校验数据集
val_data = train_data[i * num_val_samples : (i+1) * num_val_samples]
val_targets = train_targets[i* num_val_samples : (i+1) * num_val_samples]

#把剩下的k-1分数据作为训练数据,如果第i分数据作为校验数据，那么把前i-1份和第i份之后的数据连起来
partial_train_data = np.concatenate([train_data[: i * num_val_samples],
train_data[(i+1) * num_val_samples:]], axis = 0)
partial_train_targets = np.concatenate([train_targets[: i * num_val_samples],
train_targets[(i+1) * num_val_samples: ]],
axis = 0)
print("build model")
model = build_model()
#把分割好的训练数据和校验数据输入网络
history = model.fit(partial_train_data, partial_train_targets,
validation_data=(val_data, val_targets),
epochs = num_epochs,
batch_size = 1, verbose = 0)
mae_history = history.history['val_mean_absolute_error']
all_mae_histories.append(mae_history)```

```average_mae_history = [
np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)
]```

```import matplotlib.pyplot as plt
plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()```

```def smooth_curve(points, factor=0.9):
smoothed_points = []
for point in points:
if smoothed_points:
previous = smoothed_points[-1]
smoothed_points.append(previous * factor + point * (1 - factor))
else:
smoothed_points.append(point)
return smoothed_points

smooth_mae_history = smooth_curve(average_mae_history[10:])

plt.plot(range(1, len(smooth_mae_history)+1), smooth_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()```

```model = build_model()
model.fit(train_data, train_targets, epochs = 30, batch_size = 16, verbose = 0)
test_mse_score, test_mae_score = model.evaluate(test_data, test_targets)
print(test_mae_score)```

138 篇文章39 人订阅

0 条评论

## 相关文章

46913

3729

1043

### 决策树案例：基于python的商品购买能力预测系统

1 决策树/判定树（decision tree) ---- 1 决策树（Dicision Tree）是机器学习有监督算法中分类算法的一种，有关机器学习中分类和...

7197

3456

3749

### 2.4 估值和模拟

Exponentially weighted moving average（指数加权移动平均）

1943

1482

22610

4815