理解keras的波士顿房价代码中[ np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]

python深度学习第三章有一个波士顿房价的内容分析。
其中,计算所有轮次中的 K 折验证分数平均值

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

这个代码不太好直接理解,换个角度,等价于如下代码:

mean = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
print('mean - ', mean)
z = []
for i in range(num_epochs):
    temp = []
    for j in all_mae_histories:
        temp.append(j[i])
    z.append(np.mean(temp))
print('mean z ', z)

上面代码是来自stackoverflow中有人提问,下面的回答的。比起之前的代码更加好理解。
我们查看all_mean_history(我自己命名的是all_mae_score):
在这里插入图片描述
发现是里面有4个数组,每个数组包含500个数据。我们从书中可以了解到
上述代码是4折交叉验证(k=4),而每折交叉验证都要500次完整训练(epochs=500),所以,all_mae_score包含四个数组,每个数组都包含一折交叉验证的数据,也就是500个数据
在这里插入图片描述
至于为什么for循环是epochs在外面,all_mae_history在里面,因为我们最终要画图,图的横坐标是epoch,也就是说,每个epoch为横坐标,该epoch对应的4折mae的平均值为纵坐标

在这里插入图片描述
可以看到,横坐标是epoch,就像小标题写的那样,表示每个轮次(epoch)中的K折验证分数平均值。所以必然epoch是外循环了。

如果我们对最开始的代码扣细点,可以这么理解:
我们的average_mae_history是个数组,所以average_mae_history=[ ]
然后我们是要循环num_epochs次,故代码:for i in range(num_epochs)
而每个epoch我们都要计算4折交叉验证的输出,所以我们需要遍历4个交叉验证的输出数据数组,取得对应epoch的值,所以:x[i] for x in all_mae_histories,然后每次epoch对应的4个数据又构成了一个数组,所以加个中括号:[x[i] for x in all_mae_histories],然后我们调用mean方法对每个epoch对应数组值求平均,所以:np.mean()又来了。最终输出的average_mae_history是一个包含500个数据的数组。代表500个epoch对应的4折交叉验证数据平均值,然后我们再画图。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
修正后的代码如下: ```python from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from scipy import stats import tensorflow as tf import numpy as np import skfuzzy as fuzz # 分割训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) # 对特征进行模糊化处理 X_train_fuzzy = [] X_test_fuzzy = [] for i in range(X_train.shape[1]): fuzzy_vals = fuzz.trimf(X_train[:,i], [np.min(X_train[:,i]), np.mean(X_train[:,i]), np.max(X_train[:,i])]) X_train_fuzzy.append(fuzzy_vals) fuzzy_vals = fuzz.trimf(X_test[:,i], [np.min(X_train[:,i]), np.mean(X_train[:,i]), np.max(X_train[:,i])]) X_test_fuzzy.append(fuzzy_vals) X_train_fuzzy = np.array(X_train_fuzzy).T X_test_fuzzy = np.array(X_test_fuzzy).T # 构建深度神经模糊网络 model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_dim=X_train_fuzzy.shape[1]), tf.keras.layers.Dense(32, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) model.fit(X_train_fuzzy, y_train, epochs=10, batch_size=32) # 训练随机森林分类器 rf_clf = RandomForestClassifier(n_estimators=100, max_depth=5) rf_clf.fit(model.predict(X_train_fuzzy), y_train) # 预测新数据点 new_data = np.random.rand(5) new_data_fuzzy = [] for i in range(new_data.shape[0]): fuzzy_val = fuzz.interp_membership(np.linspace(np.min(X[:,i]), np.max(X[:,i]), 100), fuzz.trimf(np.linspace(np.min(X[:,i]), np.max(X[:,i]), 100), [np.min(X[:,i]), np.mean(X[:,i]), np.max(X[:,i])]), new_data[i]) new_data_fuzzy.append(fuzzy_val) new_data_fuzzy = np.array(new_data_fuzzy).reshape(1,-1) # 使用模型和随机森林分类器进行预测 if rf_clf.predict(model.predict(new_data_fuzzy)) == 1: print("New data belongs to class 1.") else: print("New data belongs to class 0.") ``` 修改的部分包括: 1. 对训练集和测试集都进行了模糊化处理。 2. 修正了模型的训练,使用训练集进行训练。 3. 对新数据进行模糊化处理,并使用模型和随机森林分类器进行预测。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值