如何在TensorFlow中获得线性回归的正确答案?

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

它没有给出期望的输出。它给出的权重和偏置值是nan

import tensorflow as tfimport matplotlib.pyplot as pltimport numpy as npimport pandas as pd# In[20]:#Getting DataFramestrain_data = pd.read_csv('train.csv')test_data = pd.read_csv('test.csv')#Dropping NaN rowstrain_data.dropna()test_data.dropna()#Getting features and labelsX_train = train_data.iloc[:,0].valuesY_train = train_data.iloc[:,1].valuestest_X = test_data.iloc[:,0].valuestest_Y = test_data.iloc[:,1].values#Plotting Training Dataplt.scatter(X_train,Y_train)# In[58]:#Training the modelX = 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 + bcost = 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

权重和偏置值变成了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的文档,这里第一个参数是所需张量的形状。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注