我尝试使用Tensorflow来实现一个非线性回归(基于Tanh(x)有4个线性项和4个非线性项)。在
平方误差之和被认为是最小的,只会增加。经过相对较少的训练步骤后,权重和偏差变为“inf”
应该有一个直接的解决方案,类似于OLS系数
细节 输入.csv是一张1323x5的桌子。因变量(y)是第一列,其余列(X1到X4)是四个特性。在
前几行显示在这里
[
代码计算并比较两个模型 a) 基于OLS的多元线性模型 b) 采用4个线性输出加4个非线性输入的混合Q模型。该模型在TensorFlow中实现
下面列出了python代码。它部分基于this Stack Overlow question
import pandas as pd, numpy as np, tensorflow as tf
from tqdm import tqdm as metered #progress bar
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn import preprocessing
# pandas data
df_train = d.read_csv(r'C:\Ajax\DS\inputs1.csv',sep="|")
obs=df_train.shape[0]
cols=df_train.shape[1]-1
dblcols = cols*2
graph = tf.get_default_graph()
# tf variables
x_ = tf.placeholder(name="input", shape=[None, cols], dtype=np.float32)
y_ = tf.placeholder(name="output", shape=[None, 1], dtype=np.float32)
wts = tf.Variable(tf.random_normal([dblcols,1]), name='weight')
b = tf.Variable(tf.random_normal([]), name='bias')
dependents= df_train["Y"].values.reshape(-1, 1)
feats = df_train.iloc[:, 1:1+cols].values.reshape(-1, cols)
本节实现OLS(多元线性回归)
^{pr2}$本部分实现了包含4个线性项和4个非线性项的Q模型
agg= tf.concat((x_ , tf.tanh(x_)),axis=1)
Qmodel = tf.add(tf.matmul(agg, wts) , b)
ssq = tf.square(y_ - Qmodel, name='cost')
ssq1= tf.reduce_sum(ssq)
LR=.01
train_op = tf.train.GradientDescentOptimizer(LR).minimize(ssq1)
nz = preprocessing.MaxAbsScaler()
Zfeats1 = nz.fit_transform(feats)
Zfeats = Zfeats1 - np.mean(Zfeats1,axis=0)
print("\nNormalized feats\n", Zfeats[:9,:],"\nstdev=",np.std(Zfeats),"\n" )
n_epochs = 10000
train_errors, nt_errors, weights, biases = [],[],[],[]
config = tf.ConfigProto(device_count = {'GPU': 0})
fig, ax = plt.subplots()
fig = plt.gcf()
fig.set_size_inches(7, 7)
ax.set_ylabel(r'Prediction', fontsize=15)
ax.set_xlabel(r'Actual', fontsize=15)
ax.set_title('OLS and Q predictors')
ax.grid(True)
fig.tight_layout()
训练循环:
with tf.Session(config=config) as sess:
sess.run(tf.global_variables_initializer())
for i in metered(range(n_epochs)):
uu, err2, weight, bias = sess.run([train_op, ssq1, wts, b],
feed_dict={x_: Zfeats, y_: dependents})
out1.append(uu)
nt_errors.append(err2)
weights.append(weight)
biases.append(bias)
NN_yhat = sess.run(Qmodel, feed_dict={x_: Zfeats})
ax.scatter(dependents, NN_yhat, c='red', label='Q')
ax.scatter(dependents, OLS_Yhat, c='blue', label='OLS')
plt.legend()
plt.show()
该代码旨在将两个模型(垂直轴上)生成的预测与实际数据(水平轴上)进行比较
注意,权重和偏差呈指数级增加,并在10到30次迭代后变为无穷大或NAN。平方误差之和随时间呈指数增长。在
将学习率从0.01降到0.001没有多大帮助。它需要3倍的时间,但是误差单调增加,最终权重变成inf
OLS模型可以看到蓝色。但是Qmodel无法显示,显然是因为返回了一个1323x1的nan数组作为NN_yhat返回
我还想知道为什么没有人返回uu。在
目前没有回答
相关问题 更多 >
编程相关推荐