前端機器學習——邏輯迴歸傳送門 哈,如今咱們再跳回機器學習的入門模型——線性迴歸,上一波咱們使用邏輯迴歸完成了一個用戶喜好顏色預測的功能,那麼咱們此次就用線性迴歸完成一個將好多點擬合在一條線上的功能,嘿嘿,仍是蠻實用,echarts.js自己是自帶這個功能的。javascript
咱們的目的就是求出這一系列的w。那麼接下來就說怎麼找到合適的w。html
function MyGetline(x, y) {
//咱們使用梯度降低法,因此要求梯度方向
const gradient = function(x, h, y) {
let g = []
for(let j = 0; j < x[0].length; j++) {
let c = 0
for(let i = 0; i < y.length; i++) {
c = c + x[i][j] * (h[i] - y[i])
}
c = c / y.length
g.push(c)
}
return g
}
//線性迴歸過程x,y是入參和輸出數組,lr是學習率(沿梯度方向降低距離),count是重複次數
function Line_Regression(x, y, lr=0.000001, count=50000) {
let w = []
x.map(item => {
item.push(1)
})
for(let i = 0; i < x[0].length; i++) {
w.push(0)
}
for(let m = 0; m < count; m++) {
let z = []
for(let i = 0; i < x.length; i++) {
let item = 0
for(let j = 0; j < w.length; j++) {
item = item + x[i][j] * w[j]
}
z.push(item)
}
let g = gradient(x, z, y)
for(let i = 0; i < w.length; i++) {
w[i] = w[i] - lr * g[i]
}
}
return w
}
let w = Line_Regression(x,y)
//返回w係數
return w
}
複製代碼
把下面的代碼複製到echart.js的在線編輯器上去,就能夠直接看效果而且隨心修修改改了 (注:在3D散點圖的實例提供的那個編輯界面有效,隨便找個折線圖實例進入編輯器是不行的哦 )前端
$.get(ROOT_PATH + 'data/asset/data/life-expectancy-table.json', function (data) {
let symbolSize = 2.5;
let mydata = []
let x = []
let y = []
for(let i=0; i<500; i++) {
let a = i * Math.random() * 10
let b = i * Math.random() * 10
let c = 9 * a + 14 * b + (Math.random() - 0.5) * i * 30
let item = []
item.push(a)
item.push(b)
item.push(c)
let xitem = []
xitem.push(a)
xitem.push(b)
x.push(xitem)
y.push(c)
mydata.push(item)
}
console.log(mydata)
option = {
grid3D: {},
xAxis3D: {},
yAxis3D: {},
zAxis3D: {},
dataset: {
source: mydata
},
series: [
{
type: 'scatter3D',
symbolSize: symbolSize
}
]
};
myChart.setOption(option);
//入參x是輸入因變量數組,入參y是輸出數組
function MyGetline(x, y) {
//梯度方向
const gradient = function(x, h, y) {
let g = []
for(let j = 0; j < x[0].length; j++) {
let c = 0
for(let i = 0; i < y.length; i++) {
c = c + x[i][j] * (h[i] - y[i])
}
c = c / y.length
g.push(c)
}
return g
}
//邏輯迴歸過程
function Line_Regression(x, y, lr=0.0000001, count=50000) {
let w = []
x.map(item => {
item.push(1)
})
for(let i = 0; i < x[0].length; i++) {
w.push(0)
}
for(let m = 0; m < count; m++) {
let z = []
for(let i = 0; i < x.length; i++) {
let item = 0
for(let j = 0; j < w.length; j++) {
item = item + x[i][j] * w[j]
}
z.push(item)
}
let g = gradient(x, z, y)
for(let i = 0; i < w.length; i++) {
w[i] = w[i] - lr * g[i]
}
// l = loss(h, y)
}
return w
}
let w = Line_Regression(x,y)
//使用求出的權重係數進行選擇
console.log(w)
}
MyGetline(x,y)
});
複製代碼