gpt4 book ai didi

python - Tensorflow:将变量嵌入矩阵并求解

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:17 24 4
gpt4 key购买 nike

抱歉,如果标题不是很清楚...我正在尝试使用 Tensorflow 求解以下问题中的“w”值:

Y = X*B(w) + e

其中 Y 是 22x5 矩阵,X 是 22x3 矩阵,B(w) 是 3*5 矩阵,其结构如下:

B = [[1, 1, 1, 1, 1], 
[exp(-3w), exp(-6w), exp(-12w), exp(-24w), exp(-36w)],
[3*exp(-3w), 6*exp(-6w), 12*exp(-12w), 24*exp(-24w), 36*exp(-36w)]]

这是我的代码:

# Parameters
learning_rate = 0.01
display_step = 50
tolerance = 0.0000000000000001

# Training Data
Y_T = df.values
X_T = factors.values


X = tf.placeholder("float32", shape = (22, 3))
Y = tf.placeholder("float32", shape = (22, 5))
w = tf.Variable(1.0, name="w")

def slope_loading(q):
return tf.exp(tf.multiply(tf.negative(q),w))

def curve_loading(q):
return tf.multiply(w,tf.exp(tf.multiply(tf.negative(q),w)))

B = tf.Variable([[1.0, 1.0, 1.0, 1.0, 1.0],
[slope_loading(float(x)) for x in [3, 6, 12, 24, 36]],
[curve_loading(float(x)) for x in [3, 6, 12, 24, 36]]])

pred = tf.matmul(X,B)
cost = tf.matmul(tf.transpose(Y-pred), (Y-pred))/22
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

# Launch the graph
with tf.Session() as sess:

# Set initial values for weights
sess.run(init)

# Set initial values for the error tolerance
tol = abs(sess.run(cost, feed_dict={X: X_T, Y: Y_T})[0][0])

iteration = 0

while tol > tolerance:

c_old = sess.run(cost, feed_dict={X: X_T, Y: Y_T})[0][0]
sess.run(optimizer, feed_dict={X: X_T, Y: Y_T})
c_new = sess.run(cost, feed_dict={X: X_T, Y: Y_T})[0][0]
tol = abs(c_new - c_old)

iteration = iteration + 1

if iteration % display_step == 0:
print("Iteration= ", iteration, "Gain= ", tol)

training_cost = sess.run(cost, feed_dict={X: X_T, Y: Y_T})

但是我收到错误“FailedPreconditionError(请参阅上面的回溯):尝试使用未初始化的值...”

我猜这与我构建 B 并将其传递给成本函数的方式有关,但我对 Tensorflow 太陌生,看不出我做错了什么。

有什么帮助吗?

最佳答案

不能使用一个变量来定义另一个变量的初始值。更好的构造B的方式是这样的

ones = tf.ones(5)
vals = tf.constant([3.0, 6.0, 12.0, 24.0, 36.0])
slopes = slope_loading(vals)
curves = curve_loading(vals)

B = tf.stack([ones, slopes, curves])

关于python - Tensorflow:将变量嵌入矩阵并求解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46435578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com