【发布时间】:2019-05-30 14:17:59
【问题描述】:
上下文:我正在尝试创建一个通用函数,以使用多项式回归(任何指定程度)来优化任何回归问题的成本。 我正在尝试使我的模型适合 load_boston 数据集(以房价作为标签和 13 个特征)。
我使用了多项式多项式,以及多个学习率和时期(使用梯度下降),即使在训练数据集上,MSE 也非常高(我使用 100% 的数据来训练模型,我正在检查相同数据的成本,但 MSE 成本仍然很高)。
import tensorflow as tf
from sklearn.datasets import load_boston
def polynomial(x, coeffs):
y = 0
for i in range(len(coeffs)):
y += coeffs[i]*x**i
return y
def initial_parameters(dimensions, data_type, degree): # list number of dims/features and degree
thetas = [tf.Variable(0, dtype=data_type)] # the constant theta/bias
for i in range(degree):
thetas.append(tf.Variable( tf.zeros([dimensions, 1], dtype=data_type)))
return thetas
def regression_error(x, y, thetas):
hx = thetas[0] # constant thetas - no need to have 1 for each variable (e.g x^0*th + y^0*th...)
for i in range(1, len(thetas)):
hx = tf.add(hx, tf.matmul( tf.pow(x, i), thetas[i]))
return tf.reduce_mean(tf.squared_difference(hx, y))
def polynomial_regression(x, y, data_type, degree, learning_rate, epoch): #features=dimensions=variables
thetas = initial_parameters(x.shape[1], data_type, degree)
cost = regression_error(x, y, thetas)
init = tf.initialize_all_variables()
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
with tf.Session() as sess:
sess.run(init)
for epoch in range(epoch):
sess.run(optimizer)
return cost.eval()
x, y = load_boston(True) # yes just use the entire dataset
for deg in range(1, 2):
for lr in range(-8, -5):
error = polynomial_regression(x, y, tf.float64, deg, 10**lr, 100 )
print (deg, lr, error)
即使大多数标签都在 30 左右(度数 = 1,学习率 = 10^-6),它也输出 97.3。 代码有什么问题?
【问题讨论】:
-
您是否更改了优化器?我建议使用AdamOptimizer,因为它在大多数情况下学习得更快。
标签: python python-3.x tensorflow machine-learning data-science