- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试编写一个简单的 tensorflow 线性回归模型,该模型采用波士顿住房数据的子集,特别是房间数(RM)列作为自变量,中位价格 (MEDV) 作为因变量,并对其应用梯度下降算法。
但是,当我运行它时,优化器似乎不起作用。成本永远不会减少,重量实际上会以错误的方向增加。
这是我构建的各种图
x 和 y 的散点图
PCA分析图
原始数据拟合
测试数据拟合。
图片在这里:
我的程序的输出如下所示:
Epoch: 0050 cost= 6393135366144.000000000 W = 110392.0 b = 456112.0
Epoch: 0100 cost= 6418308005888.000000000 W = 111131.0 b = 459181.0
Epoch: 0150 cost= 6418496225280.000000000 W = 111136.0 b = 459203.0
Epoch: 0200 cost= 6418497798144.000000000 W = 111136.0 b = 459203.0
...
Epoch: 1000 cost= 6418497798144.000000000 W = 111136.0 b = 459203.0
请注意,成本永远不会减少,事实上,重量在应该减少时会略有增加。
我不知道为什么会发生这种情况。据我所知,数据似乎是合理的,但我不知道为什么优化器不起作用。代码本身只是一个标准的 tensorflow 线性回归示例,我从互联网上下载并针对我的数据集进行了修改。
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.mlab import PCA
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import tensorflow as tf
import sys
from sklearn import model_selection
from sklearn import preprocessing
np.set_printoptions(precision=3,suppress=True)
def pca(dataset):
plt.scatter(dataset[:,0],dataset[:,1])
plt.plot()
plt.show()
results = PCA(dataset)
x = []
y = []
for item in results.Y:
x.append(item[0])
y.append(item[1])
plt.close('all')
fig1 = plt.figure()
pltData = [x,y]
plt.scatter(pltData[0],pltData[1],c='b')
xAxisLine = ((min(pltData[0]),max(pltData[0])),(0,0),(0,0))
yAxisLine = ((min(pltData[1]),max(pltData[1])),(0,0),(0,0))
plt.xlabel('RM')
plt.ylabel('MEDV')
plt.show()
rng = np.random
# learning_rate is the alpha value that we pass to the gradient descent algorithm.
learning_rate = 0.1
# How many cycles we're going to run to try and get our optimum fit.
training_epochs = 1000
display_step = 50
# We're going to pull in a the csv file and extract the X value (RM) and Y value (MEDV)
boston_dataset = pd.read_csv('data/housing.csv')
label = boston_dataset['MEDV']
features = boston_dataset['RM'].reshape(-1,1)
dataset = np.asarray(boston_dataset['RM'])
dataset = np.column_stack((np.asarray(boston_dataset['RM']),np.asarray(boston_dataset['MEDV'])))
pca(dataset)
train_X, test_X, train_Y, test_Y = model_selection.train_test_split(features, label, test_size = 0.33,
random_state = 5)
scaler = preprocessing.StandardScaler()
train_X = scaler.fit_transform(train_X)
# This is the total number of data samples that we're going to run through.
n_samples = train_X.shape[0]
# Variable placeholders.
X = tf.placeholder('float')
Y = tf.placeholder('float')
W = tf.Variable(rng.randn(), name = 'weight')
b = tf.Variable(rng.randn(), name = 'bias')
# Here we describe our training model. It's a linear regression model using the standard y = mx + b
# point slope formula. We calculate the cost by using least mean squares.
# This is our prediction algorithm: y = mx + b
prediction = tf.add(tf.multiply(X,W),b)
# Let's now calculate the cost of the prediction algorithm using least mean squares
training_cost = tf.reduce_sum(tf.pow(prediction-Y,2))/(2 * n_samples)
# This is our gradient descent optimizer algorithm. We're passing in alpha, our learning rate
# and we want the minimum value of the training cost.
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(training_cost)
init = tf.global_variables_initializer()
# Now we'll run our training data through our model.
with tf.Session() as tf_session:
# Initialize all of our tensorflow variables.
tf_session.run(init)
# We'll run the data through for 1000 times (The value of training_epochs).
for epoch in range(training_epochs):
# For each training cycle, pass in the x and y values to our optimizer algorithm to calculate the cost.
for (x,y) in zip(train_X,train_Y):
tf_session.run(optimizer,feed_dict = {X: x, Y: y})
# For every fifty cycles, let's check and see how we're doing.
if (epoch + 1 ) % 50 == 0:
c = tf_session.run(training_cost,feed_dict = {X: train_X, Y: train_Y})
print ('Epoch: ', '%04d' %
(epoch+1),'cost=','{:.9f}'.format(c), \
'W = ',tf_session.run(W), 'b = ',tf_session.run(b))
print ('Optimization finished')
print ('Training cost = ',training_cost,' W = ',tf_session.run(W), ' b = ', tf_session.run(b),'\n')
plt.plot(train_X, train_Y, 'ro',label='Original data')
plt.plot(train_X,tf_session.run(W) * train_X + tf_session.run(b), label = 'Fitted line')
plt.legend()
plt.show()
# We're now going to run test data to see how well our trained model works.
print ('Testing...(mean square loss comparison)')
testing_cost = tf_session.run(tf.reduce_sum(tf.pow(prediction - Y, 2)) / (2 * test_Y.shape[0]), feed_dict = {X: test_X, Y: test_Y})
print ('Testing cost = ',testing_cost)
print ('Absolute mean square loss difference: ', abs(training_cost - testing_cost))
plt.plot(test_X,test_Y,'bo',label='Testing data')
plt.plot(test_X,tf_session.run(W) * test_X + tf_session.run(b), label = 'Fitted line')
plt.legend()
plt.show()
`
我真的不知道为什么优化器不能正常工作因此,如果有人能指出我正确的方向,我将非常感激。
谢谢
最佳答案
这可能与你的学习率有关。尝试减少它或在几个时期后更新。
例如,如果您使用 100 个 epoch,请尝试将学习率设置为 0.01,并在 30 个 epoch 后将其降低到 0.001,然后在超过 30 或 40 个 epoch 后再次降低到 0.0001。
您可以检查 AlexNet 等常见架构的学习率更新,以便您有一个想法。
祝你好运
关于machine-learning - 我无法让我的 tensorflow 梯度下降线性回归算法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46575238/
滑动窗口限流 滑动窗口限流是一种常用的限流算法,通过维护一个固定大小的窗口,在单位时间内允许通过的请求次数不超过设定的阈值。具体来说,滑动窗口限流算法通常包括以下几个步骤: 初始化:设置窗口
表达式求值:一个只有+,-,*,/的表达式,没有括号 一种神奇的做法:使用数组存储数字和运算符,先把优先级别高的乘法和除法计算出来,再计算加法和减法 int GetVal(string s){
【算法】前缀和 题目 先来看一道题目:(前缀和模板题) 已知一个数组A[],现在想要求出其中一些数字的和。 输入格式: 先是整数N,M,表示一共有N个数字,有M组询问 接下来有N个数,表示A[1]..
1.前序遍历 根-左-右的顺序遍历,可以使用递归 void preOrder(Node *u){ if(u==NULL)return; printf("%d ",u->val);
先看题目 物品不能分隔,必须全部取走或者留下,因此称为01背包 (只有不取和取两种状态) 看第一个样例 我们需要把4个物品装入一个容量为10的背包 我们可以简化问题,从小到大入手分析 weightva
我最近在一次采访中遇到了这个问题: 给出以下矩阵: [[ R R R R R R], [ R B B B R R], [ B R R R B B], [ R B R R R R]] 找出是否有任
我正在尝试通过 C++ 算法从我的 outlook 帐户发送一封电子邮件,该帐户已经打开并记录,但真的不知道从哪里开始(对于 outlook-c++ 集成),谷歌也没有帮我这么多。任何提示将不胜感激。
我发现自己像这样编写了一个手工制作的 while 循环: std::list foo; // In my case, map, but list is simpler auto currentPoin
我有用于检测正方形的 opencv 代码。现在我想在检测正方形后,代码运行另一个命令。 代码如下: #include "cv.h" #include "cxcore.h" #include "high
我正在尝试模拟一个 matlab 函数“imfill”来填充二进制图像(1 和 0 的二维矩阵)。 我想在矩阵中指定一个起点,并像 imfill 的 4 连接版本那样进行洪水填充。 这是否已经存在于
我正在阅读 Robert Sedgewick 的《C++ 算法》。 Basic recurrences section it was mentioned as 这种循环出现在循环输入以消除一个项目的递
我正在思考如何在我的日历中生成代表任务的数据结构(仅供我个人使用)。我有来自 DBMS 的按日期排序的任务记录,如下所示: 买牛奶(18.1.2013) 任务日期 (2013-01-15) 任务标签(
输入一个未排序的整数数组A[1..n]只有 O(d) :(d int) 计算每个元素在单次迭代中出现在列表中的次数。 map 是balanced Binary Search Tree基于确保 O(nl
我遇到了一个问题,但我仍然不知道如何解决。我想出了如何用蛮力的方式来做到这一点,但是当有成千上万的元素时它就不起作用了。 Problem: Say you are given the followin
我有一个列表列表。 L1= [[...][...][.......].......]如果我在展平列表后获取所有元素并从中提取唯一值,那么我会得到一个列表 L2。我有另一个列表 L3,它是 L2 的某个
我们得到二维矩阵数组(假设长度为 i 和宽度为 j)和整数 k我们必须找到包含这个或更大总和的最小矩形的大小F.e k=7 4 1 1 1 1 1 4 4 Anwser是2,因为4+4=8 >= 7,
我实行 3 类倒制,每周换类。顺序为早类 (m)、晚类 (n) 和下午类 (a)。我固定的订单,即它永远不会改变,即使那个星期不工作也是如此。 我创建了一个函数来获取 ISO 周数。当我给它一个日期时
假设我们有一个输入,它是一个元素列表: {a, b, c, d, e, f} 还有不同的集合,可能包含这些元素的任意组合,也可能包含不在输入列表中的其他元素: A:{e,f} B:{d,f,a} C:
我有一个子集算法,可以找到给定集合的所有子集。原始集合的问题在于它是一个不断增长的集合,如果向其中添加元素,我需要再次重新计算它的子集。 有没有一种方法可以优化子集算法,该算法可以从最后一个计算点重新
我有一个包含 100 万个符号及其预期频率的表格。 我想通过为每个符号分配一个唯一(且前缀唯一)的可变长度位串来压缩这些符号的序列,然后将它们连接在一起以表示序列。 我想分配这些位串,以使编码序列的预
我是一名优秀的程序员,十分优秀!