用 Python 神经网络预测汽车保险支出

用 Python 神经网络预测汽车保险支出!保险该如何正确购买呢? 为新数据集开发神经网络预测模型可能具有挑战性。 一种方法是首先检查数据集并为可能使用的模型开发思路,然后探索数据集上简单模型的学习动态,然后最后使用健壮的测试工具为数据集开发和调整模型。此过程可用于为分类和回归预测建模问题开发有效的神经网络模型。 在本教程中,您将发现如何为瑞典汽车保险回归数据集开发多层Perceptron神经网络模型。完成本教程后,您将知道: 如何加载和汇总瑞典汽车保险数据集,以及如何使用结果建议要使用的数据准备和模型配置。 如何探索简单的MLP模型的学习动态以及... 阅读详情

为新数据集开发神经网络预测模型可能具有挑战性。

一种方法是首先检查数据集并为可能使用的模型开发思路,然后探索数据集上简单模型的学习动态,然后最后使用健壮的测试工具为数据集开发和调整模型。此过程可用于为分类和回归预测建模问题开发有效的神经网络模型。

在本教程中,您将发现如何为瑞典汽车保险回归数据集开发多层Perceptron神经网络模型。完成本教程后,您将知道:

  • 如何加载和汇总瑞典汽车保险数据集,以及如何使用结果建议要使用的数据准备和模型配置。

  • 如何探索简单的MLP模型的学习动态以及数据集上的数据转换。

  • 如何开发出对模型性能的可靠估计,调整模型性能以及对新数据进行预测。

教程概述

本教程分为四个部分。他们是:

  • 汽车保险回归数据集

  • 首个MLP和学习动力

  • 评估和调整MLP模型

  • 最终模型和做出预测

汽车保险回归数据集

第一步是定义和探索数据集。我们将使用“汽车保险”标准回归数据集。该数据集描述了瑞典的汽车保险。只有一个输入变量,即索赔的数量,目标变量是以数千瑞典克朗为单位的索赔总额。目的是在给定索赔数量的情况下预测总付款额。

您可以在此处了解有关数据集的更多信息:

  • 汽车保险数据集(auto-insurance.csv)

  • 汽车保险数据集详细信息(auto-insurance.names)

您可以在下面看到数据集的前几行。

108,392.5
19,46.2
13,15.7
124,422.2
40,119.4

我们可以看到这些值是数字的,范围从几十到几百。这表明在使用神经网络进行建模时,某种类型的缩放比例适合于数据。

我们可以直接从URL将数据集作为pandas DataFrame加载;例如:

# load the dataset and summarize the shape
from pandas import read_csv
# define the location of the dataset
url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
# load the dataset
df = read_csv(url, header=None)
# summarize shape
print(df.shape)

运行示例将直接从URL加载数据集并报告数据集的形状。

在这种情况下,我们可以确认该数据集具有两个变量(一个输入和一个输出),并且该数据集具有63行数据。

对于神经网络来说,这不是很多数据行,这表明一个小型的网络(可能带有正则化)将是合适的。

这也表明使用k倍交叉验证是一个好主意,因为与火车/测试拆分相比,它可以提供更可靠的模型性能估算值,并且因为单个模型可以在数秒而不是数小时或数天的时间内完成拟合。最大的数据集。

(63, 2)

接下来,我们可以通过查看摘要统计信息和数据图来了解有关数据集的更多信息。

# show summary statistics and plots of the dataset
from pandas import read_csv
from matplotlib import pyplot
# define the location of the dataset
url = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
# load the dataset
df = read_csv(url, header=None)
# show summary statistics
print(df.describe())
# plot histograms
df.hist()
pyplot.show()

运行示例之前,先加载数据,然后输出每个变量的摘要统计信息

我们可以看到每个变量的平均值在十个以内,范围从0到数百。这证实了缩放数据可能是一个好主意。

                0           1
count   63.000000   63.000000
mean    22.904762   98.187302
std     23.351946   87.327553
min      0.000000    0.000000
25%      7.500000   38.850000
50%     14.000000   73.400000
75%     29.000000  140.000000
max    124.000000  422.200000

然后为每个变量创建一个直方图。

我们可以看到每个变量都有相似的分布。它看起来像偏态的高斯分布或指数分布。

我们可以在每个变量上使用幂变换来降低概率分布的偏斜度,这可能会提高模型性能。

现在我们已经熟悉了数据集,让我们探讨如何开发神经网络模型。

首个MLP和学习动力

我们将使用TensorFlow为数据集开发一个多层感知器(MLP)模型。我们不知道学习超参数的哪种模型架构对这个数据集将是好的还是最好的,所以我们必须进行实验并发现什么是行之有效的。假设数据集很小,则小批量可能是个好主意,例如8或16行。入门时,使用Adam版本的随机梯度下降法是一个好主意,因为它会自动适应学习率,并且在大多数数据集上都能很好地工作。在认真评估模型之前,最好回顾一下学习动态并调整模型体系结构和学习配置,直到我们拥有稳定的学习动态,然后再充分利用模型。

我们可以通过简单的训练/测试数据拆分并查看学习曲线图来实现。这将帮助我们了解我们是学习过度还是学习不足;然后我们可以相应地调整配置。首先,我们可以将数据集分为输入和输出变量,然后分为67/33训练和测试集。

# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# split into train and test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)

接下来,我们可以定义一个最小的MLP模型。在这种情况下,我们将使用一个包含10个节点的隐藏层和一个输出层(任意选择)。我们将在隐藏层中使用ReLU激活功能和“ he_normal”权重初始化,因为它们是一种很好的做法。

模型的输出是线性激活(不激活),我们将最小化均方误差(MSE)损失。

# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')

我们将模型拟合为100个训练时期(任意选择),批量为8个,因为它是一个很小的数据集。我们正在原始数据上拟合模型,我们认为这可能不是一个好主意,但这是一个重要的起点。

# fit the model
history = model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0, validation_data=(X_test,y_test))

在训练结束时,我们将评估模型在测试数据集上的性能,并将性能报告为平均绝对误差(MAE),我通常更喜欢MSE或RMSE。

# predict test set
yhat = model.predict(X_test)
# evaluate predictions
score = mean_absolute_error(y_test, yhat)
print('MAE: %.3f' % score)

最后,我们将在训练期间在训练和测试集上绘制MSE损失的学习曲线。

# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Mean Squared Error')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()

综上所述,下面列出了评估我们在汽车保险数据集上的第一个MLP的完整示例。

# fit a simple mlp model and review learning curves
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# split into train and test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
history = model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0, validation_data=(X_test,y_test))
# predict test set
yhat = model.predict(X_test)
# evaluate predictions
score = mean_absolute_error(y_test, yhat)
print('MAE: %.3f' % score)
# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Mean Squared Error')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()

运行示例首先使模型适合训练数据集,然后报告测试数据集的MAE。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到该模型实现了大约33.2的MAE,这是性能的良好基准,我们可能可以对其进行改进。

MAE: 33.233

然后在火车和测试装置上创建MSE的线图。

我们可以看到该模型具有良好的拟合度,并且收敛良好。模型的配置是一个很好的起点。

到目前为止,学习动力很好,MAE是一个粗略的估计,不应该被依赖。

我们可能可以稍微增加模型的容量,并期待类似的学习动态。例如,我们可以添加具有八个节点(任意选择)的第二个隐藏层,并将训练时期数增加一倍至200。

# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))

完整实例如下:

# fit a deeper mlp model and review learning curves
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# split into train and test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))
# predict test set
yhat = model.predict(X_test)
# evaluate predictions
score = mean_absolute_error(y_test, yhat)
print('MAE: %.3f' % score)
# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Mean Squared Error')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()

运行示例首先使模型适合训练数据集,然后报告测试数据集的MAE。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到MAE略有改善,约为27.9,尽管训练/测试拆分的高方差意味着该评估是不可靠的。

MAE: 27.939

然后绘制MSE训练和测试集的学习曲线。我们可以看到,正如预期的那样,该模型在合理的迭代次数内实现了良好的拟合和收敛。

最后,我们可以尝试转换数据,看看它如何影响学习动力。

在这种情况下,我们将使用幂变换来减少数据分布的偏差。这还将自动标准化变量,以使它们的平均值为零,标准偏差为1,这是使用神经网络进行建模时的一种好习惯。

首先,我们必须确保目标变量是二维数组。

# ensure that the target variable is a 2d array
y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))

接下来,我们可以将PowerTransformer应用于输入变量和目标变量。

这可以通过首先将转换适合训练数据,然后转换训练和测试集来实现。

此过程将分别应用于输入和输出变量,以避免数据泄漏。

# power transform input data
pt1 = PowerTransformer()
pt1.fit(X_train)
X_train = pt1.transform(X_train)
X_test = pt1.transform(X_test)
# power transform output data
pt2 = PowerTransformer()
pt2.fit(y_train)
y_train = pt2.transform(y_train)
y_test = pt2.transform(y_test)

然后将数据用于拟合模型。

后面可以根据模型做出的预测以及测试集中的预期目标值对变换进行求逆,我们可以像以前一样以正确的比例计算MAE。

# inverse transforms on target variable
y_test = pt2.inverse_transform(y_test)
yhat = pt2.inverse_transform(yhat)

结合在一起,下面列出了使用转换后的数据拟合和评估MLP以及创建模型的学习曲线的完整示例。

# fit a mlp model with data transforms and review learning curves
from pandas import read_csv
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import PowerTransformer
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# split into train and test datasets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
# ensure that the target variable is a 2d array
y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))
# power transform input data
pt1 = PowerTransformer()
pt1.fit(X_train)
X_train = pt1.transform(X_train)
X_test = pt1.transform(X_test)
# power transform output data
pt2 = PowerTransformer()
pt2.fit(y_train)
y_train = pt2.transform(y_train)
y_test = pt2.transform(y_test)
# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
history = model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0, validation_data=(X_test,y_test))
# predict test set
yhat = model.predict(X_test)
# inverse transforms on target variable
y_test = pt2.inverse_transform(y_test)
yhat = pt2.inverse_transform(yhat)
# evaluate predictions
score = mean_absolute_error(y_test, yhat)
print('MAE: %.3f' % score)
# plot learning curves
pyplot.title('Learning Curves')
pyplot.xlabel('Epoch')
pyplot.ylabel('Mean Squared Error')
pyplot.plot(history.history['loss'], label='train')
pyplot.plot(history.history['val_loss'], label='val')
pyplot.legend()
pyplot.show()

运行示例首先使模型适合训练数据集,然后报告测试数据集的MAE。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,该模型可以达到合理的MAE分数,尽管比以前报告的性能差。我们暂时将忽略模型性能。

MAE: 34.320

创建了学习曲线的线图,表明该模型达到了合理的拟合并且有足够的时间收敛。

现在,我们对带有或不带有数据转换的简单MLP模型的学习动态有了一些了解,现在我们可以看一下评估模型的性能以及调整模型的配置。

评估和调整MLP模型

k倍交叉验证过程可以提供更可靠的MLP性能估计,尽管它可能非常慢。这是因为必须拟合和评估k个模型。当数据集大小较小时(例如汽车保险数据集),这不是问题。我们可以使用KFold类创建拆分并手动枚举每个折叠,拟合模型,对其进行评估,然后在过程结束时报告评估分数的平均值。

# prepare cross validation
kfold = KFold(10)
# enumerate splits
scores = list()
for train_ix, test_ix in kfold.split(X, y):
 # fit and evaluate the model...
 ...
...
# summarize all scores
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

我们可以使用此框架通过一系列不同的数据准备,模型架构和学习配置来开发MLP模型性能的可靠估计。

重要的是,在使用k-fold交叉验证来评估性能之前,我们首先对上一部分中的数据集模型的学习动态有了了解。如果我们开始直接调整模型,我们可能会获得良好的结果,但是如果没有,我们可能不知道为什么,例如 模型超出或不足。

如果我们再次对模型进行较大的更改,则最好返回并确认模型正在适当收敛。

下面列出了评估上一节中的基本MLP模型的此框架的完整示例。

# k-fold cross-validation of base model for the auto insurance regression dataset
from numpy import mean
from numpy import std
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# prepare cross validation
kfold = KFold(10)
# enumerate splits
scores = list()
for train_ix, test_ix in kfold.split(X, y):
 # split data
 X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]
 # determine the number of input features
 n_features = X.shape[1]
 # define model
 model = Sequential()
 model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
 model.add(Dense(1))
 # compile the model
 model.compile(optimizer='adam', loss='mse')
 # fit the model
 model.fit(X_train, y_train, epochs=100, batch_size=8, verbose=0)
 # predict test set
 yhat = model.predict(X_test)
 # evaluate predictions
 score = mean_absolute_error(y_test, yhat)
 print('>%.3f' % score)
 scores.append(score)
# summarize all scores
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

运行示例将在评估过程的每次迭代中报告模型性能,并在运行结束时报告MAE的平均值和标准偏差。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到MLP模型的MAE约为38.913。

我们将使用此结果作为基准,以查看是否可以实现更好的性能。

>27.314
>69.577
>20.891
>14.810
>13.412
>69.540
>25.612
>49.508
>35.769
>62.696
Mean MAE: 38.913 (21.056)

首先,让我们尝试在原始数据集上评估更深的模型,以查看其性能是否比基准模型更好。

# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)

完整实例如下:

# k-fold cross-validation of deeper model for the auto insurance regression dataset
from numpy import mean
from numpy import std
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# prepare cross validation
kfold = KFold(10)
# enumerate splits
scores = list()
for train_ix, test_ix in kfold.split(X, y):
 # split data
 X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]
 # determine the number of input features
 n_features = X.shape[1]
 # define model
 model = Sequential()
 model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
 model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
 model.add(Dense(1))
 # compile the model
 model.compile(optimizer='adam', loss='mse')
 # fit the model
 model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)
 # predict test set
 yhat = model.predict(X_test)
 # evaluate predictions
 score = mean_absolute_error(y_test, yhat)
 print('>%.3f' % score)
 scores.append(score)
# summarize all scores
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

运行报告运行结束时MAE的平均值和标准偏差。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到MLP模型获得的MAE约为35.384,这略好于获得MAE约为38.913的基线模型。

Mean MAE: 35.384 (14.951)

接下来,让我们尝试使用与上一节相同的对输入和目标变量进行幂变换的模型。

下面列出了完整的示例。

# k-fold cross-validation of deeper model with data transforms
from numpy import mean
from numpy import std
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import PowerTransformer
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# prepare cross validation
kfold = KFold(10)
# enumerate splits
scores = list()
for train_ix, test_ix in kfold.split(X, y):
 # split data
 X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]
 # ensure target is a 2d array
 y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))
 # prepare input data
 pt1 = PowerTransformer()
 pt1.fit(X_train)
 X_train = pt1.transform(X_train)
 X_test = pt1.transform(X_test)
 # prepare target
 pt2 = PowerTransformer()
 pt2.fit(y_train)
 y_train = pt2.transform(y_train)
 y_test = pt2.transform(y_test)
 # determine the number of input features
 n_features = X.shape[1]
 # define model
 model = Sequential()
 model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
 model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
 model.add(Dense(1))
 # compile the model
 model.compile(optimizer='adam', loss='mse')
 # fit the model
 model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)
 # predict test set
 yhat = model.predict(X_test)
 # inverse transforms
 y_test = pt2.inverse_transform(y_test)
 yhat = pt2.inverse_transform(yhat)
 # evaluate predictions
 score = mean_absolute_error(y_test, yhat)
 print('>%.3f' % score)
 scores.append(score)
# summarize all scores
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

运行报告运行结束时MAE的平均值和标准偏差。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到MLP模型获得的MAE约为37.371,这比基准模型好,但不比更深的基准模型好。

也许这种转变没有我们最初认为的那样有用。

Mean MAE: 37.371 (29.326)

另一种变换是对输入变量和目标变量进行规范化。

这意味着将每个变量的值缩放到[0,1]范围。我们可以使用MinMaxScaler来实现。例如:

# prepare input data
pt1 = MinMaxScaler()
pt1.fit(X_train)
X_train = pt1.transform(X_train)
X_test = pt1.transform(X_test)
# prepare target
pt2 = MinMaxScaler()
pt2.fit(y_train)
y_train = pt2.transform(y_train)
y_test = pt2.transform(y_test)

结合在一起,下面列出了使用数据规范化评估更深层MLP的完整示例。

# k-fold cross-validation of deeper model with normalization transforms
from numpy import mean
from numpy import std
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from matplotlib import pyplot
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# prepare cross validation
kfold = KFold(10)
# enumerate splits
scores = list()
for train_ix, test_ix in kfold.split(X, y):
 # split data
 X_train, X_test, y_train, y_test = X[train_ix], X[test_ix], y[train_ix], y[test_ix]
 # ensure target is a 2d array
 y_train, y_test = y_train.reshape((len(y_train),1)), y_test.reshape((len(y_test),1))
 # prepare input data
 pt1 = MinMaxScaler()
 pt1.fit(X_train)
 X_train = pt1.transform(X_train)
 X_test = pt1.transform(X_test)
 # prepare target
 pt2 = MinMaxScaler()
 pt2.fit(y_train)
 y_train = pt2.transform(y_train)
 y_test = pt2.transform(y_test)
 # determine the number of input features
 n_features = X.shape[1]
 # define model
 model = Sequential()
 model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
 model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
 model.add(Dense(1))
 # compile the model
 model.compile(optimizer='adam', loss='mse')
 # fit the model
 model.fit(X_train, y_train, epochs=200, batch_size=8, verbose=0)
 # predict test set
 yhat = model.predict(X_test)
 # inverse transforms
 y_test = pt2.inverse_transform(y_test)
 yhat = pt2.inverse_transform(yhat)
 # evaluate predictions
 score = mean_absolute_error(y_test, yhat)
 print('>%.3f' % score)
 scores.append(score)
# summarize all scores
print('Mean MAE: %.3f (%.3f)' % (mean(scores), std(scores)))

运行报告运行结束时MAE的平均值和标准偏差。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到MLP模型获得的MAE约为30.388,这比我们迄今为止尝试过的任何其他配置都要好。

Mean MAE: 30.388 (14.258)

我们可以继续测试模型架构的替代配置(更多或更少的节点或层),学习超参数(更多或更少的批处理)以及数据转换。

我将其保留为练习;让我知道你发现了什么。您可以获得更好的结果吗?

将您的结果发表在下面的评论中,我很乐意看到您所得到的。

接下来,让我们看看如何拟合最终模型并使用它进行预测。

最终模型和做出预测

选择模型配置后,我们可以在所有可用数据上训练最终模型,并使用它对新数据进行预测。在这种情况下,我们将使用数据标准化的更深层模型作为最终模型。这意味着,如果我们想将模型保存到文件中,则必须保存模型本身(用于进行预测),输入数据的转换(用于新的输入数据)和目标变量的转换(用于新预测)。尽管可以在整个数据集而不是数据集的训练子集上,但我们仍可以像以前一样准备数据并拟合模型。

# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# ensure target is a 2d array
y = y.reshape((len(y),1))
# prepare input data
pt1 = MinMaxScaler()
pt1.fit(X)
X = pt1.transform(X)
# prepare target
pt2 = MinMaxScaler()
pt2.fit(y)
y = pt2.transform(y)
# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')

然后,我们可以使用此模型对新数据进行预测。首先,我们可以定义一行新数据,这只是该数据集的一个变量。

# define a row of new data
row = [13]

然后,我们可以转换此新数据,以准备用作模型的输入。

# transform the input data
X_new = pt1.transform([row])

然后我们可以做出预测。

# make prediction
yhat = model.predict(X_new)

然后将预测的变换反转,以便我们可以按正确的比例使用或解释结果。

# invert transform on prediction
yhat = pt2.inverse_transform(yhat)

在这种情况下,我们将仅报告预测。

# report prediction
print('f(%s) = %.3f' % (row, yhat[0]))

综上所述,下面列出了为汽车保险数据集拟合最终模型并使用其对新数据进行预测的完整示例。

# fit a final model and make predictions on new data.
from pandas import read_csv
from sklearn.model_selection import KFold
from sklearn.metrics import mean_absolute_error
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
# load the dataset
path = 'https://raw.githubusercontent.com/jbrownlee/Datasets/master/auto-insurance.csv'
df = read_csv(path, header=None)
# split into input and output columns
X, y = df.values[:, :-1], df.values[:, -1]
# ensure target is a 2d array
y = y.reshape((len(y),1))
# prepare input data
pt1 = MinMaxScaler()
pt1.fit(X)
X = pt1.transform(X)
# prepare target
pt2 = MinMaxScaler()
pt2.fit(y)
y = pt2.transform(y)
# determine the number of input features
n_features = X.shape[1]
# define model
model = Sequential()
model.add(Dense(10, activation='relu', kernel_initializer='he_normal', input_shape=(n_features,)))
model.add(Dense(8, activation='relu', kernel_initializer='he_normal'))
model.add(Dense(1))
# compile the model
model.compile(optimizer='adam', loss='mse')
# fit the model
model.fit(X, y, epochs=200, batch_size=8, verbose=0)
# define a row of new data
row = [13]
# transform the input data
X_new = pt1.transform([row])
# make prediction
yhat = model.predict(X_new)
# invert transform on prediction
yhat = pt2.inverse_transform(yhat)
# report prediction
print('f(%s) = %.3f' % (row, yhat[0]))

运行示例可以使模型适合整个数据集,并为单行新数据做出预测。

注意:由于算法或评估程序的随机性,或者数值精度的差异,您的结果可能会有所不同。考虑运行该示例几次并比较平均结果。

在这种情况下,我们可以看到输入13导致输出62(千瑞典克朗)。

f([13]) = 62.595

作者:沂水寒城,优快云博客专家,个人研究方向:机器学习、深度学习、NLP、CV

Blog: http://yishuihancheng.blog.youkuaiyun.com

文末福利

各位猿们,还在为记不住API发愁吗,哈哈哈,最近发现了国外大师整理了一份Python代码速查表和Pycharm快捷键sheet,火爆国外,这里分享给大家。

这个是一份Python代码速查表

下面的宝藏图片是2张(windows && Mac)高清的PyCharm快捷键一览图

怎样获取呢?可以添加我们的AI派团队的Beyonce小姐姐

一定要备注【高清图】哦

????????????????????

➕我们的Beyonce小姐姐微信要记得备注【高清图】哦

来都来了,喜欢的话就请分享、点赞、在看三连再走吧~~~

Android14 RK3576开发板有线网卡静态IP配置全攻略(附数据库修改详解) 本文详细介绍了在Android 14 RK3576开发板上实现有线网卡出厂默认静态IP配置的完整方案。通过深入修改系统源码和SettingsProvider数据库,扩展全局设置字段并注入默认值,确保设备首次启动即自动应用预设的IP地址、子网掩码、网关和DNS,适用于工业控制、数字标牌等批量部署场景,有效提升生产效率。 阅读详情

相关推荐

超详细Tokenizer——文本训练数据预处理

Tokenizer是Keras库中的一个文本处理工具,它用于将文本分词并构建词汇表,同时将文本映射到整数序列。这对于自然语言处理任务非常有用,例如文本分类、情感分析、机器翻译等。

halo的博客 3703

【Keras】keras model.compile(loss='目标函数 ', optimizer='adam', metrics=['accuracy'])

讲解了各种loss https://www.cnblogs.com/smuxiaolei/p/8662177.html

mjiansun的专栏 6151

Pytorch学习笔记(III)——提取特征

目录一、引言二、具体步骤1、参数模型2、网络结构3、参数载入4、特征提取器5、读取图片三、完整代码 一、引言   深度学习在许多任务中主要充当着特征学习的作用,而学习完的特征才是后续应用的一个关键。本文将主要介绍,如何提取任意目标层的特征图。   本文以输入数据为图片为例。 二、具体步骤 1、参数模型 博主使用了ResNet50训练了一个人脸识别的网络   训练完成的深度学习模型,我们会保存一...

lockonlxf的博客 2645

基于Keras框架的自定义数据集卷积神经网络(CNN)用于回归预测,并讨论调参减小模型大小送入stm32板子

搭建可以送入stm32板子的keras框架的CNN网络,使用自定义数据集做回归预测,自己编写了完整的CNN代码。由于是新手刚学习python,有不对或者代码繁琐的请多多指教。

qq_48411488的博客 1650

利用GBD数据库做未来疾病负担预测

最近看到一篇文献,利用GBD数据库中的数据对疾病负担的发展趋势进行预测。觉得很有趣,就抽空用R语言复盘了一下里面关键的方法。 参考文献: Changing trends in the disease burden of esophageal cancer in China from 1990 to 2017 and its predicted level in 25 years DOI: 10.1002/cam4.3775 1. 相关R包的安装 主要用到的R包有3个,一个一个讲: 1.1 Nordpred

NickyCat的博客 5万+

从SC7A20数据手册到代码:一步步搞定加速度值读取与换算(避坑指南)

本文详细解析了SC7A20三轴加速度传感器的数据手册,从寄存器配置到原始数据读取,再到加速度值的换算方法。通过代码示例和避坑指南,帮助开发者准确实现加速度值的读取与换算,适用于嵌入式开发和运动检测应用。

weixin_26878995的博客 588

用yolox算法模型实现自动标注

用YOLOX实现自动标注

weixin_37933097的博客 4768

ST-Link V2的隐藏技能:多通道串口调试的终极指南

本文深入探讨了ST-Link V2的多通道串口调试功能,突破传统烧录工具的限制。通过详细的硬件配置、Arduino IDE设置和实战案例,展示了如何利用SWD接口实现多通道数据监控,提升STM32F103C8T6等开发板的调试效率。文章还提供了PCB布局优化和性能调优技巧,助力开发者充分发挥ST-Link V2的潜能。

weixin_29285605的博客 357

使用pyplot一定要记得close

1、不关闭将会引起什么问题 在一个循环中,如果我们的目的是每一个循环都做一副图出来,如果做完一副图,没有使用pyplot.close(),就会使之前做过的图出现在下一副上,看下图: 我们的目的 而如果你的目的是每一对train,test都做一张图,就要使用pyplot.close()每一次循环后关闭pyplot,即使在函数中也要这么做。改正后如下: 详细代码如下 plt.plot(hist...

aachangs的博客 1万+

[SV]SystemVerilog状态机实现案例

本文介绍了SystemVerilog中状态机的实现方法。首先使用枚举类型定义状态(TOP_HIB、TOP_BG、TOP_LDO、TOP_NOR),然后通过三个主要任务实现状态机:1)格式化现态寄存器处理状态转换;2)描述状态转移条件,包括计时器和稳定时间判断;3)基于当前状态和输入信号确定次态。状态机在时钟边沿或复位时更新状态,实现了从休眠到正常工作状态的转换逻辑,包含电源稳定时间检测等关键功能。

元直的博客 2022

倍福--实现TCP/IP的配置

控制器为CX5120,需要和上位机做通信,选择TCP/IP的通讯方式,本文介绍TCP/IP通信的操作步骤。 目 录 软硬件版本 3 1.1. 倍福Beckhoff 3 1.1.1. 控制器硬件 3 1.1.2. 控制软件 3 1.2. 串口调试助手 3 1.2.1. TCP调试通信助手 3 授权文件 3 2.1 Lib文件 3 2.2. CAB文件 4 PLC程序编写 4 3.1. 引入TCP/IP库文件 4 3.2. Client端程序 5 3.2.1. 建立相关变量 5 3.3.2. 编写连接功能块

weixin_41883890的博客 5730

python多因素电力预测——基于LSTM神经网络

一个很简易的多因素预测电力模型,所用数据量很少,所以效果不是很好,如果数据量大,可能最后的模型精度和效果会不错,看看就行了,写的很乱(数据来源于泰迪杯最先公布的数据)。 # -*- coding: utf-8 -*- # @Time : 2022/3/26 15:13 # @Author : 中意灬 # @FileName: 多变量.py # @Software: PyCharm import numpy as np import matplotlib.pyplot as plt import seab

qq_55977554的博客 4446

磁悬浮分子泵:起源、现状与未来趋势深度解析

摘要 磁悬浮分子泵作为高真空获取的关键设备,通过磁悬浮技术实现转子无接触高速运转,大幅提升了真空系统的性能和可靠性。本文系统梳理了分子泵从机械轴承到磁悬浮的技术演变历程,分析了当前行业格局及主要厂商产品特性,包括爱德华兹、普发真空等国际巨头的技术优势。研究进一步探讨了磁悬浮分子泵在半导体制造、科研设备等领域的核心应用,通过数学模型揭示了其性能参数关系。最后,展望了未来在智能化、节能化等方面的发展趋势,为相关领域的技术创新提供参考。 关键词:磁悬浮分子泵;高真空技术;半导体制造;科研设备;技术发展

技术工作者 691

python在Keras中使用LSTM解决序列问题

时间序列预测是指我们必须根据时间相关的输入来预测结果的问题类型。时间序列数据的典型示例是股市数据,其中股价随时间变化。 递归神经网络(RNN)已被证明可以有效解决序列问题。特别地,作为RNN的变体的长期短期记忆网络(LSTM)当前正在各种领域中用于解决序列问题。LSTM神经网络架构和原理及其在Python中的预测应用序列问题可以大致分为以下几类: 在本文中,我们将了解如何使用LSTM及其不同的变体来解决一对一和多对一的序列问题。 阅读本文后,您将能够基于历史数据解决诸如股价预测,天气预报等问题。由于文本也是

拓端研究室TRL 1252

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

history = model.fit(train_X, train_y, epochs=200, batch_size=batchsize, validation_data=(test_X, tes...

history = model.fit(train_X, train_y, epochs=200, batch_size=batchsize, validation_data=(test_X, test_y)) train_X: 训练数据的输入特征, 一般是numpy数组或者tensorflow张量 train_y: 训练数据的标签, 一般是numpy数组或者tensorflow张量 epoch...

weixin_42575505的博客 1168

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

gru matlab实现,分别用CNN、GRU和LSTM实现时间序列预测(2019-04-06)

卷积神经网络(CNN)、长短期记忆网络(LSTM)以及门控单元网络(GRU)是最常见的一类算法,在kaggle比赛中经常被用来做预测和回归。今天,我们就抛砖引玉,做一个简单的教程,如何用这些网络预测时间序列。因为是做一个简单教程,所以本例子中网络的层数和每层的神经元个数没有调试到最佳。根据不同的数据集,同学们可以自己调网络结构和具体参数。1.环境搭建我们运行的环境是下载anaconda,然后在里面...

weixin_42511098的博客 5218

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

波士顿房价预测(Python深度学习——回归问题)

记:电影评论分类,新闻分类不同的是预测房价不属于分类问题,而是回归问题,所用的损失函数以及验证方法也与前面由很大的不同。 1、回归与logistic回归:很容易将这两个混为一谈,从名字来看好像这两个都是回归算法,但其实logistic回归是分类算法。 2、回归问题:相对于分类问题的目标是预测输入数据点所对应的单一离散的标签来说,回归问题是预测一个连续值而不是离散的标签,例如根据掌握的气象数据来预测明天的气温等。 3、波士顿房价数据集:是20世纪70年代中期波士顿郊区房价的中位数,该数据集的数据点相对较

qq_38938670的博客 6685

基于自动编码器特征抽取的分类实战

【翻译自: Autoencoder Feature Extraction for Classification】 【说明:Jason BrownleePhD大神的文章个人很喜欢,所以闲暇时间里会做一点翻译和学习实践的工作,这里是相应工作的实践记录,希望能帮到有需要的人!】 自动编码器是一种神经网络,可用于学习原始数据的压缩表示。自动编码器由编码器和解码器子模型组成。编码器压缩输入,而解码器尝试根据编码器提供的压缩版本重新创建输入。训练后,将保存编码器模型,并丢弃解码...

Together_CZ的博客 1万+

fit函数 model_深度学习笔记38_利用回调函数保存最佳的模型

利用回调函数保存最佳的模型ModelCheckpoint 与 EarlyStopping回调函数对于EarlyStopping回调函数,最好的使用场景就是,如果我们发现经过了数轮后,目标指标不再有改善了,就可以提前终止,这样就节省时间。该函数的具体参数如下: keras.callbacks.EarlyStopping( monitor='val_loss', min_delta=0, patie...

weixin_39824223的博客 1691

Python实现预测客户是否会购买房车险源码+数据集,基于伯努利朴素贝叶斯预测客户购买房车险源码,Python预测客户购买房车险

根据2000年数据挑战赛保险公司的客户特征数据,预测客户是否会购买房车险。使用伯努利朴素贝叶斯模型,我获得了更好的预测效果。

Python代码大全 1603

Python 中解释 XGBoost 模型的学习曲线

XGBoost是梯度提升集成算法的强大而有效的实现。配置XGBoost模型的超参数可能具有挑战性,这通常会导致使用既费时又计算量大的大型网格搜索实验。配置XGBoost模型的另一种方法是在...

Python中文社区 4935

自编码器 AE(AutoEncoder)程序

1.程序讲解 (1)香草编码器 在这种自编码器的最简单结构中,只有三个网络层,即只有一个隐藏层的神经网络。它的输入和输出是相同的,可通过使用Adam优化器和均方误差损失函数,来学习如何重构输入。 在这里,如果隐含层维数(64)小于输入维数(784),则称这个编码器是有损的。通过这个约束,来迫使神经网络来学习数据的压缩表征。 input_size = 784 hidden_size = 6......

zbzcDZF的博客 5170

多变量LSTM模型

多变量时间序列数据是指每个时间步长有多个观察值的数据。 对于多变量时间序列数据,我们可能需要两种主要模型;他们是: 多输入系列。 多个并联系列。 1、多输入系列 问题可能有两个或更多并行输入时间序列和输出时间序列,这取决于输入时间序列。 输入时间序列是平行的,因为每个系列在同一时间步骤具有观察。 我们可以通过两个并行输入时间序列的简单示例来演示这一点,其中输出序列是输入序列的简单添加...

ssjdoudou的博客 2万+

基于Keras的OpenAI-gym强化学习的车杆/FlappyBird游戏

强化学习 课程:Q-Learning强化学习(李宏毅)、深度强化学习 强化学习是一种允许你创造能从环境中交互学习的AI Agent的机器学习算法,其通过试错来学习。如上图所示,大脑代表AI Agent并在环境中活动。当每次行动过后,Agent接收到环境反馈。反馈包括回报Reward和环境的下个状态State,回报由模型设计者定义。如果类比人类学习自行车,可以将车从起始点到当前位...

aohun0743的博客 2082

keras中的目标函数和优化函数

目标函数就是我们常说的损失函数,优化函数就是我们常说的反调参数的函数,包括:梯度下降函数、随机梯度下降函数等。 这些我相信大家都很清楚了,下面我就简单的介绍一下keras提供的常见的目标函数和优化函数,本人能力有限,平时用到的酒多说几句,用不到的就把名字写出来,欢迎大家补充和指正。 目标函数: keras文档:  http://keras.io/objectives/ mean_s

zjm750617105的专栏 2万+
上一篇: 详细教程!手把手教你制作个人微信红包封面
下一篇: 机器学习100天—第5天k近邻法(附实战教程)
Wang_AI
博客等级 码龄12年 996粉丝 162原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值