如何打印出Tensorflow中使用的多元线性回归模型的方程?

2024-09-29 23:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

对于python中Tensorflow中的多元线性回归模型,如何打印出模型用于预测标签的方程。我目前使用的模型使用两个特征来预测一个标签,因此我认为一般方程是this,但是如何使用Tensorflow获得所有常数的未知参数和值呢

代码:

fundingFeatures = fundingTrainSet.copy()
fundingLabels = fundingFeatures.pop('% of total funding spent')
fundingFeatures = np.array(fundingFeatures)
normalizer = preprocessing.Normalization()
normalizer.adapt(fundingFeatures)
model = tf.keras.Sequential([
    normalizer,
    layers.Dense(units=1)
])
model.compile(loss = tf.losses.MeanSquaredError(),
                      optimizer = tf.keras.optimizers.SGD(
    learning_rate=0.06, momentum=0.0, nesterov=True, name="SGD",
))
model.fit(fundingFeatures, fundingLabels, epochs=1000)

Tags: 模型modeltftensorflow常数线性特征标签
1条回答
网友
1楼 · 发布于 2024-09-29 23:30:15

我将解释如何写出NN的方程

为了做到这一点,我修改了代码,并为Y要素和Y标签添加了固定值。我这样做是为了一步一步地展示整个计算过程,这样下次你就可以自己做了

根据你提供的所有信息,你似乎

  1. NN具有2层
  2. 第一层是规范化层
  3. 第二层是致密层
  4. 在输入张量中有两个特征,一个输出

让我们从规范化层开始。对于规范化层,我认为使用术语“权重”有点“奇怪”。重量基本上是 将应用于每个输入的均值和方差,以使数据正常化

我将调用两个输入特征x0和x1

如果运行我的代码(这是包含固定数据的代码),您将看到规范化层的权重为

[5.4.6] [5.4 11.24]

这意味着[x0-x1]列的平均值为[5.4.6],方差为[5.4 11.24]

我们能核实一下吗?是的,我们可以。让我们检查x0

[1,4,8,7,3,6,6,5,2,8,5]
mean = 5
stddev = 2.323790008
variance = 5.4 ( variance = stddev^2)

如您所见,它与规范化层的“权重”匹配

当数据被推送到标准化层时,每个值都将基于 x'=(x-平均值)/STDEV(STDEV,非方差)

您可以通过对数据应用规范化来检查这一点。 在代码中,如果运行这两行

normalized_data = normalizer(fundingFeatures)

print(normalized_data)

你会得到

[[-1.7213259   1.31241   ]
 [-0.43033147  1.014135  ]
 [ 1.2909944   0.41758505]
 [ 0.86066294 -0.47723997]
 [-0.86066294 -1.07379   ]
 [ 0.43033147  1.31241   ]
 [ 0.43033147 -1.07379   ]
 [ 0.         -1.07379   ]
 [-1.2909944   0.71586   ]
 [ 1.2909944  -1.07379   ]]
 

让我们验证一下第一个数字

x0[0] = 1
x0'[0] = (1-5)/2.323790008 = -1.7213 ( it does match)

在这一点上,我们应该能够编写规范化层的方程

y[0]' = (x0-5)/2.323790008   # (x-mean)/stddev
y[1]' = (x1-4.6)/3.352610923

现在,这两个输出将被注入下一层。记住,你有一个致密的层,因此它是完全连通的。这意味着两个值都将注入单个神经元

这些线显示密集层的权重和偏移值

weights = model.layers[1].get_weights()[0]
biases = model.layers[1].get_weights()[1]

print(weights)
print(biases)


[[-0.12915221]
 [-0.41322172]]
[0.32663438]

神经元将每个输入乘以给定的权重,将所有结果加上偏差。 让我们修改y[0]'和y[1]'以包含权重

y[0]' = (x0-5)/2.323790008)* -0.12915221
y[1]' = (x1-4.6)/3.352610923 * -0.41322172

我们很接近了,我们只需要把这两个加起来,再加上偏差

y' = ((x0-5)/2.323790008)* -0.12915221 + (x1-4.6)/3.352610923 * -0.41322172 + 0.32663438

既然你没有激活功能,我们就到此为止

我们如何验证公式是否正确? 让我们使用这个模型来预测随机输入的标签,看看它是否与我们在等式中输入相同值时得到的结果相匹配

首先,让我们为[4,5]运行一个模型预测

print(model.predict( [[4,5]] )) 
[[0.3329112]] 

现在,让我们将相同的输入插入到方程中

y'=((4-5)/2.323790008)*-0.12915221)+((5-4.6)/3.352610923*-0.41322172)+0.3266338

y'=0.332911

看来我们很好。我降低了一些精度,只是为了让我的生活更轻松

这是您的模型的函数。把我的号码换成你的号码

y'=((x0-5)/2.323790008)*-0.12915221+(x1-4.6)/3.352610923*-0.41322172+0.3266338

这是代码。我还添加了张力板,以便您可以验证我在这里所说的内容

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental import preprocessing
from matplotlib import pyplot as plt
import numpy as np
import datetime


fundingFeatures = tf.constant([[1, 9], [4, 8], [8, 6], [7 ,3], [3 ,1], [6, 9], [6, 1], [5, 1], [2, 7], [8, 1]], dtype=tf.int32)
fundingLabels = tf.constant([ 0.8160469,  -0.05249139,  1.1515405,   1.0792135,   0.80369186, -1.7353221,  1.0092108,   0.19228514, -0.10366996,  0.10583907])
normalizer = preprocessing.Normalization()
normalizer.adapt(fundingFeatures)

normalized_data = normalizer(fundingFeatures)

print(normalized_data)

print("Features mean raw: %.2f" % (fundingFeatures[:,0].numpy().mean()))
print("Features std raw: %.2f" % (fundingFeatures[:,0].numpy().std()))
print("Features mean raw: %.2f" % (fundingFeatures[:,1].numpy().mean()))
print("Features std raw: %.2f" % (fundingFeatures[:,1].numpy().std()))

print("Features mean: %.2f" % (normalized_data.numpy().mean()))
print("Features std: %.2f" % (normalized_data.numpy().std()))

model = tf.keras.Sequential([
    normalizer,
    layers.Dense(units=1)
])
model.compile(loss = tf.losses.MeanSquaredError(),
                      optimizer = tf.keras.optimizers.SGD(
    learning_rate=0.06, momentum=0.0, nesterov=True, name="SGD",
))


log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)

model.summary()
print('       ')
weights = model.layers[0].get_weights()[0]
biases = model.layers[0].get_weights()[1]
print('       ')


model.fit(fundingFeatures, fundingLabels, epochs=1000, callbacks=[tensorboard_callback])

weights = model.layers[0].get_weights()[0]
biases = model.layers[0].get_weights()[1]

print(weights)
print(biases)

print ("\n")

weights = model.layers[1].get_weights()[0]
biases = model.layers[1].get_weights()[1]

print(weights)
print(biases)

print('\n    - Prediction    ')

print(model.predict( [[4,5]] )) 

相关问题 更多 >

    热门问题