为什么不在python中打印值?

时间:2018-03-30 02:28:01

标签: python tensorflow

这是我的python程序片段,用Tensorflow运行线性回归:

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import xlrd

DATA_FILE = "fire_theft.xls"

#Step 1: read in data from the .xls file
book = xlrd.open_workbook(DATA_FILE, encoding_override="utf-8")
#access the first sheet in the workbook
sheet = book.sheet_by_index(0)
#start from row index 1 to row index sheet.nrows-1
data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
n_samples = sheet.nrows-1

#Step 2: create placeholders for input X (number of fire) and label Y (number
#of theft)
X = tf.placeholder(tf.float32, name="X")
Y = tf.placeholder(tf.float32, name="Y")

#Step 3: create weight and bias, initialized to 0
w = tf.Variable(0.0, name="weights")
b = tf.Variable(0.0, name="bias")

#Step 4: construct model to predict Y (number of theft) from the number of fire
Y_predicted = X * w + b

#Step 5: use the square error as the loss function
loss = tf.square(Y - Y_predicted, name="loss")

#Step 6: use gradient descent with learning rate = 0.01 to minimize loss
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)

with tf.Session() as sess:
    #Step 7: initialize the necessary variables, in this case w and b
    sess.run(tf.global_variables_initializer())

    #Step 8: train the model
    for i in range(100): #run 100 epochs
        for x, y in data:
            #Session runs train_op to minimize loss
            sess.run(optimizer, feed_dict={X: x, Y: y})

    #Step 9: output the values of w and b
    w_value, b_value = sess.run([w, b])
    print('y = ' + str(sess.run(w)) + 'x' + ' + ' + str(sess.run(b)))

但是,当在代码末尾附近调用sess.run([w,b])时,不会打印矩阵[w,b]。我不知道为什么。

此外,最后的print语句返回" y = nanx + nan"。我不确定为什么w和b都不被解释为数字。有人能帮助我吗?

顺便说一句,fire_theft.xls文件如下所示:

3.5 6

5.3 7.4

......(等)

0 个答案:

没有答案