from keras.datasets import boston_housing
(train_data,train_targets),(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 /= std
test_data -= mean
test_data /= std
#定义训练模型
from keras import models
from keras import layers
def build_model() :
model = models.Sequential()
model.add(layers.Dense(64,activation='relu',input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer = 'rmsprop',loss = 'mse',metrics = ['mae'])
return model
#k折验证,进行编写
import numpy as np
k=4
num_val_samples = len(train_data) // k
num_epochs = 100
all_scores = []
for i in range(k) :
print('processing fole#',i)
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]
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)
model = build_model()
model.fit(partial_train_data,partial_train_targets,epochs=num_epochs,batch_size=1,verbose=0)
#对模型进行评估
val_mse , val_mae = model.evaluate(val_data,val_targets,verbose=0)
all_scores.append(val_mse)
print(all_scores)
print(np.mean(all_scores))
######2022-01-15 10:33:51.192014: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
2022-01-15 10:33:51.665798: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1510] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3967 MB memory: -> device: 0, name: GeForce RTX 2060, pci bus id: 0000:01:00.0, compute capability: 7.5
2022-01-15 10:33:51.911091: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)