我没有得到线性回归问题的输出。
这是一个简单的变量线性回归问题。
我使用了Kaggle的线性回归数据集,
从这里:Linear Regression on Random Dataset

它没有给出期望的输出,而是给出了权重和偏差的nan值

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd


# In[20]:


#Getting DataFrames
train_data = pd.read_csv('train.csv')
test_data = pd.read_csv('test.csv')

#Dropping NaN rows
train_data.dropna()
test_data.dropna()

#Getting features and labels
X_train = train_data.iloc[:,0].values
Y_train = train_data.iloc[:,1].values

test_X = test_data.iloc[:,0].values
test_Y = test_data.iloc[:,1].values

#Plotting Training Data
plt.scatter(X_train,Y_train)


# In[58]:


#Training the model

X = tf.placeholder(tf.float32,name='X')
Y = tf.placeholder(tf.float32,name='Y')

W = tf.Variable(tf.random_normal([]),dtype=tf.float32,name='weights')
b = tf.Variable(tf.random_normal([]),dtype=tf.float32,name='bias')

Y_pred = W*X + b

cost = tf.square(Y_pred,name='cost')

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost)
init = tf.global_variables_initializer()


# In[61]:


with tf.Session() as sess:
    sess.run(init)
    for i in range(1000):
        sess.run(optimizer,feed_dict={X:X_train,Y:Y_train})
    W_out,b_out = sess.run([W,b])
    writer = tf.summary.FileWriter('./graphs/linear_reg', sess.graph)


print(W_out,b_out)


# In[60]:


#plt.plot(X_train, W_out*X_train + b_out, color='red')
plt.scatter(X_train,Y_train)
plt.plot(X_train, W_out*X_train + b_out, color='red')


它给出了输出:

nan nan


权重和偏见正变得越来越重要。

最佳答案

您尚未分配任何权重和偏见。您将体重定义为

W = tf.Variable(tf.random_normal([]),dtype=tf.float32,name='weights')
b = tf.Variable(tf.random_normal([]),dtype=tf.float32,name='bias')


在这里,tf.random_normal的输入是一个空数组。因此,Wb均为空。您需要指定Wb的形状,对于W将是[in_dim, out_dim],对于b将是[out_dim]。检查tf.random_normal文档,这里的第一个参数是所需张量的形状。

关于python-3.x - 如何在Tensorflow中获得线性回归的正确答案?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49351206/

10-12 19:55