如何在线性回归中拟合曲线? :Tensorflow

时间:2018-08-01 05:20:23

标签: python tensorflow machine-learning linear-regression

我一直在尝试拟合曲线。看起来像这样:

enter image description here

我正在使用均方误差成本函数。 MSE错误为19.8,并尝试将其最小化以实现最佳拟合。我应该如何做呢?这是我的代码:

# coding: utf-8

# In[1]:


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


# In[95]:


train_features = pd.read_csv("training_set_X.csv", delimiter=',')
train_observations = pd.read_csv("training_set_Y.csv", delimiter=',')

print("Training features: ")
train_features


# In[96]:


print("Training observations: ")
train_observations


# In[97]:


print("Shape of training features = ", train_features.shape)
print("Shape of training observations = ", train_observations.shape)


# In[98]:


# Normalization of training data.
train_features_stddev_arr = np.std(train_features, axis=0)
train_features_mean_arr = np.mean(train_features, axis=0)
normalized_train_features = (train_features - train_features_mean_arr) / train_features_stddev_arr


# In[99]:


print("Training features: Standard deviation....")
train_features_stddev_arr


# In[100]:


print("Training featues: Mean....")
train_features_mean_arr


# In[101]:


print("Normalized training features....")
normalized_train_features


# In[102]:


# Layer parameters.
n_nodes_h11 = 5
n_nodes_h12 = 5
n_nodes_h13 = 3
no_features = 17
learning_rate = 0.1
epochs = 200


# In[103]:


cost_history = []


# In[104]:


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


# In[105]:


# Defining weights and biases.
first_weight = tf.Variable(tf.random_normal([no_features, n_nodes_h11], stddev=np.sqrt(2/no_features)))
second_weight = tf.Variable(tf.random_normal([n_nodes_h11, n_nodes_h12], stddev=np.sqrt(2/n_nodes_h11)))
third_weight = tf.Variable(tf.random_normal([n_nodes_h12, n_nodes_h13], stddev=np.sqrt(2/n_nodes_h12)))
output_weight = tf.Variable(tf.random_normal([n_nodes_h13, 1], stddev=np.sqrt(2/n_nodes_h13)))


# In[106]:


first_bias = tf.Variable(tf.random_uniform([n_nodes_h11], -1.0, 1.0))
second_bias = tf.Variable(tf.random_uniform([n_nodes_h12], -1.0, 1.0))
third_bias = tf.Variable(tf.random_uniform([n_nodes_h13], -1.0, 1.0))
output_bias = tf.Variable(tf.random_uniform([1], -1.0, 1.0))


# In[107]:


# Defining activations of each layer.
first = tf.sigmoid(tf.matmul(X, first_weight) + first_bias)
second = tf.sigmoid(tf.matmul(first, second_weight) + second_bias)
third = tf.sigmoid(tf.matmul(second, third_weight) + third_bias)
output = tf.matmul(third, output_weight) + output_bias


# In[108]:


# Using Mean Squared Error
cost = tf.reduce_sum(tf.pow(output - Y, 2)/train_features.shape[0])


# In[109]:


# Using Gradient Descent algorithm
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)


# In[110]:


init = tf.global_variables_initializer()


# In[111]:


# Running the network.
with tf.Session() as sess:
    sess.run(init)

    for step in np.arange(epochs):
        sess.run(optimizer, feed_dict={X:normalized_train_features, Y:train_observations})
        cost_history.append(sess.run(cost, feed_dict={X:normalized_train_features, Y:train_observations}))
        print (sess.run(cost, feed_dict={X:normalized_train_features, Y:train_observations}))

    pred_y = sess.run(output, feed_dict={X:normalized_train_features})
    plt.plot(range(len(pred_y)), pred_y)
    plt.plot(range(len(train_observations)), train_observations)


# In[112]:


plt.savefig('fig2.png')
plt.show()

学习率是0.1,我使用的是随机梯度下降技术。我尝试使用学习率0.01和0.5的Adam Optimizer减少错误,但我在89.21左右出现错误。如果有人可以为我提供更好的解决方案,以减少MSE误差以获得最佳曲线拟合,那就太好了。

0 个答案:

没有答案