from keras import models
from keras import layers
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
np.set_printoptions(suppress=True)
df_iris = pd.read_csv("CCLE_ActivityArea_24_504.csv", header=0)
df_iris = df_iris.fillna(0)
iris = np.array(df_iris)
train_data = iris[0:317, 0:23]
train_targets = iris[0:317, 23]
test_data = iris[317:504, 0:23]
test_targets = []
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 = 4
num_val_samples = len(train_data) // k
num_epochs = 500
all_scores = []
all_mae_histories = []
for i in range(k):
print('正在处理fold #', 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()
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']
val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
all_scores.append(val_mae)
all_mae_histories.append(mae_history)
print("Complete!")
average_mae_history = [
np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
mean_score = np.mean(all_scores)
print("mean_score:", mean_score)
test_targets = model.predict(test_data)
print(test_targets)
# 画图
plt.plot(range(1, len(average_mae_history)+1), average_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()
一个使用两层DNN的实例
最新推荐文章于 2024-08-23 17:48:13 发布