【发布时间】:2020-05-18 07:16:21
【问题描述】:
据我了解,假设您不使用隐藏层和线性激活函数,神经网络将产生与线性回归相同的方程形式。即 y = SUM(w_i * x_i + b_i) 其中 i 是您拥有的特征数量的 0。
我试图通过使用线性回归的权重和偏差向自己证明这一点,将其输入神经网络并查看结果是否相同。他们不是。
我想知道我的理解是否不正确,或者我的代码是否正确,或者两者兼而有之。
from sklearn.linear_model import LinearRegression
import tensorflow as tf
from tensorflow import keras
import numpy as np
linearModel = LinearRegression()
linearModel.fit(np.array(normTrainFeaturesDf), np.array(trainLabelsDf))
# Gets the weights of the linear model and the intercept in a form that can be passed into the neural network
linearWeights = np.array(linearModel.coef_)
intercept = np.array([linearModel.intercept_])
trialWeights = np.reshape(linearWeights, (len(linearWeights), 1))
trialWeights = trialWeights.astype('float32')
intercept = intercept.astype('float32')
newTrialWeights = [trialWeights, intercept]
# Create a neural network and set the weights of the model to the linear model
nnModel = keras.Sequential([keras.layers.Dense(1, activation='linear', input_shape=[len(normTrainFeaturesDf.keys())]),])
nnModel.set_weights(newTrialWeights)
# Print predictions of both models (the results are vastly different)
print(linearModel.predict(np.array(normTestFeaturesDf))
print(nnModel.predict(normTestFeaturesDf).flatten())
【问题讨论】:
-
在打印结果之前您是否训练过您的神经网络?如果您没有看到的是随机初始化权重的预测。
-
@Gabriel_D nnModel.set_weights(newTrialWeights) 不是将 NN 的权重设置为线性模型的权重吗?
-
你能把它变成一个可重现的例子吗?
normTrainFeaturesDf未定义。
标签: python tensorflow machine-learning neural-network linear-regression