如何创建一个用于回归的神经网络?

17

我正在尝试使用Keras构建一个神经网络,使用的数据是https://archive.ics.uci.edu/ml/datasets/Yacht+Hydrodynamics。以下是我的代码:

import numpy as np
from keras.layers import Dense, Activation
from keras.models import Sequential
from sklearn.model_selection import train_test_split

data = np.genfromtxt(r"""file location""", delimiter=',')

model = Sequential()
model.add(Dense(32, activation = 'relu', input_dim = 6))
model.add(Dense(1,))
model.compile(optimizer='adam', loss='mean_squared_error', metrics = ['accuracy'])

Y = data[:,-1]
X = data[:, :-1]

我尝试使用 model.fit(X, Y) 进行训练,但模型的准确率一直保持在 0。由于我是 Keras 的新手,所以这可能有一个简单的解决方案,请提前谅解。

我的问题是,如何在模型中添加回归以提高准确性?感谢您的帮助。

1个回答

55
首先,你需要使用sklearn.model_selection库中的train_test_split类将数据集拆分为训练集和测试集。{{train_test_split}}
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.08, random_state = 0)

此外,您需要使用StandardScaler类对值进行scale

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

接下来,您应该添加更多的{{图层}}以获得更好的结果。

注意

通常,为了找出所需的{{隐藏}} {{图层}}的总数,应使用以下公式。

Nh = Ns/(α∗ (Ni + No))

在这里:

  • Ni = 输入神经元的数量。
  • No = 输出神经元的数量。
  • Ns = 训练数据集中的样本数。
  • α = 一个任意的缩放因子,通常为2-10。

因此,我们的分类器变成了:

# Initialising the ANN
model = Sequential()

# Adding the input layer and the first hidden layer
model.add(Dense(32, activation = 'relu', input_dim = 6))

# Adding the second hidden layer
model.add(Dense(units = 32, activation = 'relu'))

# Adding the third hidden layer
model.add(Dense(units = 32, activation = 'relu'))

# Adding the output layer
model.add(Dense(units = 1))

你使用的度量标准 metrics=['accuracy'] 对应于一个分类问题。如果你想进行回归,请删除 metrics=['accuracy']。也就是说,只需使用{{}}。
model.compile(optimizer = 'adam',loss = 'mean_squared_error')

这里是一份适用于回归分类Keras指标列表。

同时,你需要为fit方法定义batch_sizeepochs的值。

model.fit(X_train, y_train, batch_size = 10, epochs = 100)

enter image description here

在训练完神经网络network后,您可以使用model.predict方法对X_test进行预测。

y_pred = model.predict(X_test)

现在,你可以比较从神经网络预测中获得的y_pred真实数据y_test。为此,您可以使用matplotlib库创建一个plot。请注意,保留{{和}}占位符。
plt.plot(y_test, color = 'red', label = 'Real data')
plt.plot(y_pred, color = 'blue', label = 'Predicted data')
plt.title('Prediction')
plt.legend()
plt.show()

我们的神经网络似乎学得非常好

这是plot的样子。 enter image description here

这是完整的代码

import numpy as np
from keras.layers import Dense, Activation
from keras.models import Sequential
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Importing the dataset
dataset = np.genfromtxt("data.txt", delimiter='')
X = dataset[:, :-1]
y = dataset[:, -1]

# Splitting the dataset into the Training set and Test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.08, random_state = 0)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

# Initialising the ANN
model = Sequential()

# Adding the input layer and the first hidden layer
model.add(Dense(32, activation = 'relu', input_dim = 6))

# Adding the second hidden layer
model.add(Dense(units = 32, activation = 'relu'))

# Adding the third hidden layer
model.add(Dense(units = 32, activation = 'relu'))

# Adding the output layer

model.add(Dense(units = 1))

#model.add(Dense(1))
# Compiling the ANN
model.compile(optimizer = 'adam', loss = 'mean_squared_error')

# Fitting the ANN to the Training set
model.fit(X_train, y_train, batch_size = 10, epochs = 100)

y_pred = model.predict(X_test)

plt.plot(y_test, color = 'red', label = 'Real data')
plt.plot(y_pred, color = 'blue', label = 'Predicted data')
plt.title('Prediction')
plt.legend()
plt.show()

3
漂亮的回答! - MaxU - stand with Ukraine
2
了不起的 @MihaiAlexandru-Ionut,你能解释一下缩放的必要性吗? - ES1927
@ES1927,许多机器学习算法使用欧氏距离。因此需要归一化或缩放,以使所有输入处于可比较的范围内。 - Mihai Alexandru-Ionut
我在识别预测与实际绘图中的x轴代表什么方面遇到了一些困难。起初,我认为它是时期,但在我的数据中,无论我在时期中更改什么,我都得到相同的x轴范围。有人能解释一下吗? - Joehat
回答我上面的评论,它是样本编号 =) - Joehat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接