- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 Go 中实现梯度下降。我的目标是根据汽车的行驶里程来预测汽车的成本。这是我的数据集:
km,price
240000,3650
139800,3800
150500,4400
185530,4450
176000,5250
114800,5350
166800,5800
89000,5990
144500,5999
84000,6200
82029,6390
63060,6390
74000,6600
97500,6800
67000,6800
76025,6900
48235,6900
93000,6990
60949,7490
65674,7555
54000,7990
68500,7990
22899,7990
61789,8290
我尝试了各种方法,例如规范化数据集、不规范化数据集、保留 thetas 不变、非规范化 thetas...但我无法得到正确的结果。我的数学一定有什么地方不对劲,但我不知道哪里不对。我想要得到的结果应该约为 t0 = 8500, t1 = -0.02我的实现如下:
package main
import (
"encoding/csv"
"fmt"
"log"
"math"
"os"
"strconv"
)
const (
dataFile = "data.csv"
iterations = 20000
learningRate = 0.1
)
type dataSet [][]float64
var minKm, maxKm, minPrice, maxPrice float64
func (d dataSet) getExtremes(column int) (float64, float64) {
min := math.Inf(1)
max := math.Inf(-1)
for _, row := range d {
item := row[column]
if item > max {
max = item
}
if item < min {
min = item
}
}
return min, max
}
func normalizeItem(item, min, max float64) float64 {
return (item - min) / (max - min)
}
func (d *dataSet) normalize() {
minKm, maxKm = d.getExtremes(0)
minPrice, maxPrice = d.getExtremes(1)
for _, row := range *d {
row[0], row[1] = normalizeItem(row[0], minKm, maxKm), normalizeItem(row[1], minPrice, maxPrice)
}
}
func processEntry(entry []string) []float64 {
if len(entry) != 2 {
log.Fatalln("expected two fields")
}
km, err := strconv.ParseFloat(entry[0], 64)
if err != nil {
log.Fatalln(err)
}
price, err := strconv.ParseFloat(entry[1], 64)
if err != nil {
log.Fatalln(err)
}
return []float64{km, price}
}
func getData() dataSet {
file, err := os.Open(dataFile)
if err != nil {
log.Fatalln(err)
}
reader := csv.NewReader(file)
entries, err := reader.ReadAll()
if err != nil {
log.Fatalln(err)
}
entries = entries[1:]
data := make(dataSet, len(entries))
for k, entry := range entries {
data[k] = processEntry(entry)
}
return data
}
func outputResult(theta0, theta1 float64) {
file, err := os.OpenFile("weights.csv", os.O_WRONLY, 0644)
if err != nil {
log.Fatalln(err)
}
defer file.Close()
file.Truncate(0)
file.Seek(0, 0)
file.WriteString(fmt.Sprintf("theta0,%.6f\ntheta1,%.6f\n", theta0, theta1))
}
func estimatePrice(theta0, theta1, mileage float64) float64 {
return theta0 + theta1*mileage
}
func (d dataSet) computeThetas(theta0, theta1 float64) (float64, float64) {
dataSize := float64(len(d))
t0sum, t1sum := 0.0, 0.0
for _, it := range d {
mileage := it[0]
price := it[1]
err := estimatePrice(theta0, theta1, mileage) - price
t0sum += err
t1sum += err * mileage
}
return theta0 - (t0sum / dataSize * learningRate), theta1 - (t1sum / dataSize * learningRate)
}
func denormalize(theta, min, max float64) float64 {
return theta*(max-min) + min
}
func main() {
data := getData()
data.normalize()
theta0, theta1 := 0.0, 0.0
for k := 0; k < iterations; k++ {
theta0, theta1 = data.computeThetas(theta0, theta1)
}
theta0 = denormalize(theta0, minKm, maxKm)
theta1 = denormalize(theta1, minPrice, maxPrice)
outputResult(theta0, theta1)
}
为了正确实现梯度下降,我应该修复什么?
最佳答案
Linear Regression非常简单:
// yi = alpha + beta*xi + ei
func linearRegression(x, y []float64) (float64, float64) {
EX := expected(x)
EY := expected(y)
EXY := expectedXY(x, y)
EXX := expectedXY(x, x)
covariance := EXY - EX*EY
variance := EXX - EX*EX
beta := covariance / variance
alpha := EY - beta*EX
return alpha, beta
}
尝试一下 here ,输出:
8499.599649933218 -0.021448963591702314 396270.87871142407
代码:
package main
import (
"encoding/csv"
"fmt"
"strconv"
"strings"
)
func main() {
x, y := readXY(`data.csv`)
alpha, beta := linearRegression(x, y)
fmt.Println(alpha, beta, -alpha/beta) // 8499.599649933218 -0.021448963591702314 396270.87871142407
}
// https://en.wikipedia.org/wiki/Ordinary_least_squares#Simple_linear_regression_model
// yi = alpha + beta*xi + ei
func linearRegression(x, y []float64) (float64, float64) {
EX := expected(x)
EY := expected(y)
EXY := expectedXY(x, y)
EXX := expectedXY(x, x)
covariance := EXY - EX*EY
variance := EXX - EX*EX
beta := covariance / variance
alpha := EY - beta*EX
return alpha, beta
}
// E[X]
func expected(x []float64) float64 {
sum := 0.0
for _, v := range x {
sum += v
}
return sum / float64(len(x))
}
// E[XY]
func expectedXY(x, y []float64) float64 {
sum := 0.0
for i, v := range x {
sum += v * y[i]
}
return sum / float64(len(x))
}
func readXY(filename string) ([]float64, []float64) {
// file, err := os.Open(filename)
// if err != nil {
// panic(err)
// }
// defer file.Close()
file := strings.NewReader(data)
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
records = records[1:]
size := len(records)
x := make([]float64, size)
y := make([]float64, size)
for i, v := range records {
val, err := strconv.ParseFloat(v[0], 64)
if err != nil {
panic(err)
}
x[i] = val
val, err = strconv.ParseFloat(v[1], 64)
if err != nil {
panic(err)
}
y[i] = val
}
return x, y
}
var data = `km,price
240000,3650
139800,3800
150500,4400
185530,4450
176000,5250
114800,5350
166800,5800
89000,5990
144500,5999
84000,6200
82029,6390
63060,6390
74000,6600
97500,6800
67000,6800
76025,6900
48235,6900
93000,6990
60949,7490
65674,7555
54000,7990
68500,7990
22899,7990
61789,8290`
<小时/>
Gradient descent基于这样的观察:如果多变量函数 F(x) 被定义并且在点 a 的邻域中可微,则 F(x) 减小得最快,如果一个从a
沿F
在a
处的负梯度方向出发,-∇F(a)
,例如:
// F(x)
f := func(x float64) float64 {
return alpha + beta*x // write your target function here
}
导数函数:
h := 0.000001
// Derivative function ∇F(x)
df := func(x float64) float64 {
return (f(x+h) - f(x-h)) / (2 * h) // write your target function derivative here
}
搜索:
minimunAt := 1.0 // We start the search here
gamma := 0.01 // Step size multiplier
precision := 0.0000001 // Desired precision of result
max := 100000 // Maximum number of iterations
currentX := 0.0
step := 0.0
for i := 0; i < max; i++ {
currentX = minimunAt
minimunAt = currentX - gamma*df(currentX)
step = minimunAt - currentX
if math.Abs(step) <= precision {
break
}
}
fmt.Printf("Minimum at %.8f value: %v\n", minimunAt, f(minimunAt))
关于go - 实现梯度下降,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58833048/
我正在尝试调整 tf DeepDream 教程代码以使用另一个模型。现在当我调用 tf.gradients() 时: t_grad = tf.gradients(t_score, t_input)[0
考虑到 tensorflow 中 mnist 上的一个简单的小批量梯度下降问题(就像在这个 tutorial 中),我如何单独检索批次中每个示例的梯度。 tf.gradients()似乎返回批次中所有
当我在 numpy 中计算屏蔽数组的梯度时 import numpy as np import numpy.ma as ma x = np.array([100, 2, 3, 5, 5, 5, 10,
除了数值计算之外,是否有一种快速方法来获取协方差矩阵(我的网络激活)的导数? 我试图将其用作深度神经网络中成本函数中的惩罚项,但为了通过我的层反向传播误差,我需要获得导数。 在Matlab中,如果“a
我有一个计算 3D 空间标量场值的函数,所以我为它提供 x、y 和 z 坐标(由 numpy.meshgrid 获得)的 3D 张量,并在各处使用元素运算。这按预期工作。 现在我需要计算标量场的梯度。
我正在使用内核密度估计 (KDE) ( http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.gaussian_kde.htm
我对 tensorflow gradient documentation 中的示例感到困惑用于计算梯度。 a = tf.constant(0.) b = 2 * a g = tf.gradients(
我有一个 softmax 层(只有激活本身,没有将输入乘以权重的线性部分),我想对其进行向后传递。 我找到了很多关于 SO 的教程/答案来处理它,但它们似乎都使用 X 作为 (1, n_inputs)
仅供引用,我正在尝试使用 Tensorflow 实现梯度下降算法。 我有一个矩阵X [ x1 x2 x3 x4 ] [ x5 x6 x7 x8 ] 我乘以一些特征向量 Y 得到 Z [ y
我目前有一个由几百万个不均匀分布的粒子组成的体积,每个粒子都有一个属性(对于那些好奇的人来说是潜在的),我想为其计算局部力(加速度)。 np.gradient 仅适用于均匀间隔的数据,我在这里查看:S
我正在寻找有关如何实现 Gradient (steepest) Descent 的建议在 C 中。我正在寻找 f(x)=||Ax-y||^2 的最小值,其中给出了 A(n,n) 和 y(n)。 这在
我正在查看 SVM 损失和导数的代码,我确实理解了损失,但我无法理解如何以矢量化方式计算梯度 def svm_loss_vectorized(W, X, y, reg): loss = 0.0 dW
我正在寻找一种有效的方法来计算 Julia 中多维数组的导数。准确地说,我想要一个等效的 numpy.gradient在 Julia 。但是,Julia 函数 diff : 仅适用于二维数组 沿微分维
我在cathesian 2D 系统中有两个点,它们都给了我向量的起点和终点。现在我需要新向量和 x 轴之间的角度。 我知道梯度 = (y2-y1)/(x2-x1) 并且我知道角度 = arctan(g
我有一个 2D 数组正弦模式,想要绘制该函数的 x 和 y 梯度。我有一个二维数组 image_data : def get_image(params): # do some maths on
假设我有一个针对 MNIST 数据的简单 TensorFlow 模型,如下所示 import tensorflow as tf from tensorflow.examples.tutorials.m
我想查看我的 Tensorflow LSTM 随时间变化的梯度,例如,绘制从 t=N 到 t=0 的梯度范数。问题是,如何从 Tensorflow 中获取每个时间步长的梯度? 最佳答案 在图中定义:
我有一个简单的神经网络,我试图通过使用如下回调使用张量板绘制梯度: class GradientCallback(tf.keras.callbacks.Callback): console =
在CIFAR-10教程中,我注意到变量被放置在CPU内存中,但它在cifar10-train.py中有说明。它是使用单个 GPU 进行训练的。 我很困惑..图层/激活是否存储在 GPU 中?或者,梯度
我有一个 tensorflow 模型,其中层的输出是二维张量,例如 t = [[1,2], [3,4]] . 下一层需要一个由该张量的每一行组合组成的输入。也就是说,我需要把它变成t_new = [[
我是一名优秀的程序员,十分优秀!