如何创建用于回归的神经网络? [英] How to create a neural network for regression?
问题描述
我正在尝试使用Keras制作神经网络.我使用的数据是 https://archive.ics.uci.edu/ml /datasets/Yacht + Hydrodynamics .我的代码如下:
I am trying to use Keras to make a neural network. The data I am using is https://archive.ics.uci.edu/ml/datasets/Yacht+Hydrodynamics. My code is as follows:
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并不陌生,所以这可能是一个简单的解决方案,在此道歉.
From here I have tried using model.fit(X, Y), but the accuracy of the model appears to remain at 0. I am new to Keras so this is probably an easy solution, apologies in advance.
我的问题是向模型添加回归以提高准确性的最佳方法是什么?预先感谢.
My question is what is the best way to add regression to the model so that the accuracy increases? Thanks in advance.
推荐答案
首先,必须使用train_test_split
类将数据集分为training
集和test
集sklearn.model_selection
库.
First of all, you have to split your dataset into training
set and test
set using train_test_split
class from sklearn.model_selection
library.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.08, random_state = 0)
此外,您还必须使用StandardScaler
类scale
您的值.
Also, you have to scale
your values using StandardScaler
class.
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
然后,您应该添加更多的 layers 以获得更好的效果.
Then, you should add more layers in order to get better results.
注意
通常,使用以下公式来找出所需的隐藏 层的总数是一个好习惯.
Usually it's a good practice to apply following formula in order to find out the total number of hidden layers needed.
Nh = Ns/(α∗ (Ni + No))
其中
-
Ni =输入神经元的数量.
- 否=输出神经元的数量. NS =训练数据集中的样本数.
- α=通常为2-10的任意比例因子.
- Ni = number of input neurons.
- No = number of output neurons.
- Ns = number of samples in training data set.
- α = an arbitrary scaling factor usually 2-10.
因此我们的分类器变为:
So our classifier becomes:
# 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))
您使用的metric
-metrics=['accuracy']
对应于分类问题.如果要进行回归,请删除metrics=['accuracy']
.也就是说,只需使用
The metric
that you use- metrics=['accuracy']
corresponds to a classification problem. If you want to do regression, remove metrics=['accuracy']
. That is, just use
model.compile(optimizer = 'adam',loss = 'mean_squared_error')
此处是 keras的列表regression
和classification
Here is a list of keras metrics for regression
and classification
此外,您还必须为fit
方法定义batch_size
和epochs
值.
Also, you have to define the batch_size
and epochs
values for fit
method.
model.fit(X_train, y_train, batch_size = 10, epochs = 100)
训练好network
后,可以使用model.predict
方法predict
predict
的结果.
After you trained your network
you can predict
the results for X_test
using model.predict
method.
y_pred = model.predict(X_test)
现在,您可以将我们从神经网络预测中获得的y_pred
与真实数据进行比较.为此,您可以使用matplotlib
库创建plot
.
Now, you can compare the y_pred
that we obtained from neural network prediction and y_test
which is real data. For this, you can create a plot
using matplotlib
library.
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
的外观.
这是完整的代码
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()
这篇关于如何创建用于回归的神经网络?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!