css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>DeeplearnJS logistic regresion demo</title>

    <!-- deeplearn.js -->
    <script src="https://unpkg.com/deeplearn@latest"></script>
    <!-- highcharts.js -->
    <script src="https://cdn.hcharts.cn/highcharts/highcharts.js"></script>
  
</head>
<body>
    <div id="app" style="width: 500px;height:400px;"></div>
    
    <script>
      (async function() {
        Highcharts.theme = {
   colors: ['#DF5353', '#90ee7e', '#f45b5b', '#7798BF', '#aaeeee', '#ff0066',
      '#eeaaee', '#55BF3B', '#DF5353', '#7798BF', '#aaeeee'],
   chart: {
      backgroundColor: {
         linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 },
         stops: [
            [0, '#2a2a2b'],
            [1, '#3e3e40']
         ]
      },
      style: {
         fontFamily: '\'Unica One\', sans-serif'
      },
      plotBorderColor: '#606063'
   },
   title: {
      style: {
         color: '#E0E0E3',
         textTransform: 'uppercase',
         fontSize: '20px'
      }
   },
   subtitle: {
      style: {
         color: '#E0E0E3',
         textTransform: 'uppercase'
      }
   },
   xAxis: {
      gridLineColor: '#707073',
      labels: {
         style: {
            color: '#E0E0E3'
         }
      },
      lineColor: '#707073',
      minorGridLineColor: '#505053',
      tickColor: '#707073',
      title: {
         style: {
            color: '#A0A0A3'
         }
      }
   },
   yAxis: {
      gridLineColor: '#707073',
      labels: {
         style: {
            color: '#E0E0E3'
         }
      },
      lineColor: '#707073',
      minorGridLineColor: '#505053',
      tickColor: '#707073',
      tickWidth: 1,
      title: {
         style: {
            color: '#A0A0A3'
         }
      }
   },
   tooltip: {
      backgroundColor: 'rgba(0, 0, 0, 0.85)',
      style: {
         color: '#F0F0F0'
      }
   },
   
   legend: {
      itemStyle: {
         color: '#E0E0E3'
      },
      itemHoverStyle: {
         color: '#FFF'
      },
      itemHiddenStyle: {
         color: '#606063'
      }
   },
   credits: {
      style: {
         color: '#666'
      }
   },
   labels: {
      style: {
         color: '#707073'
      }
   }
};

// Apply the theme
Highcharts.setOptions(Highcharts.theme);


// 建立假資料,1 代表智商 100 分以上,0 代表智商 100 分以下
const data = [] 
for (let i=0; i<200; i++) {
    let tmpX1 = Math.random() * 120 + 60;
    let tmpX2 = Math.random() * 120 + 60;
    data.push({
        x: tmpX1,
        y: tmpX2,
        c: tmpX1 > 100 && tmpX2 > 100 ? 1: 0
    });
}

/**
 * deeplearn.js 運算
 */
const x_list = [];
const y_list = [];

for (let elem of data) {
    x_list.push([elem.x, elem.y]);
    y_list.push(elem.c);
}

const x_data = dl.tensor2d(x_list);
const y_data = dl.tensor2d(y_list);

// 權重與偏差
const W = dl.variable(dl.zeros([1, 2]));
const B = dl.variable(dl.zeros([1]));

// logistic regression 模型
const f = x => dl.sigmoid(W.matMul(x.transpose()).add(B));
// loss function(log loss)
const loss = (pred, label) => dl.mean(dl.neg(dl.sum(dl.mul(label, dl.log(pred)))));

// 梯度優化
const learningRate = 0.001;
const optimizer = dl.train.sgd(learningRate);

// Training!
for (let i = 0; i < 1000; i++) {
  const cost = optimizer.minimize(() => loss(f(x_data), y_data), true);
}


// 用 dataSync 取得 training 結果
const wPredict = W.dataSync();
const bPredict = B.dataSync();
console.log(wPredict, bPredict);

// 計算切割線段
const data_line = [
    [60, parseFloat((180 * wPredict[0] + bPredict[0])/wPredict[1])],
    [180, parseFloat((60 * wPredict[0] + bPredict[0])/wPredict[1])]
];
console.log(data_line);

        
// 繪製圖形
const data_scatter1 = [];
const data_scatter2 = [];
for (let elem of data) {
    if (elem.x > 100 && elem.y > 100) {
        data_scatter1.push([elem.x, elem.y]);
    } else {
        data_scatter2.push([elem.x, elem.y]);
    }  
}
        
// Result
const options = {
    title: {
        text: 'deeplearn.js 你是聰明人嗎?'                 
    },
    xAxis: {
        title: {
          text: '智商'                 
        },
        min: 60,
        max: 180
    },
    yAxis: {
        title: {
          text: '書讀得多寡'                 
        },
        min: 60,
        max: 180
    },
    series: [
        {
            type: 'line',
            name: 'Decision Boundary', 
            color: '#fff600',
            data: data_line
        },  
        {
            type: 'scatter',
            name: 'Smart', 
            marker: {
                symbol: 'cross',  
                radius: 4         
            },
            color: '#FF0000',
            data: data_scatter1
        },
        {
            type: 'scatter',
            name: 'Stupid',
            marker: {
                symbol: 'cross',  
                radius: 4         
            },
            color: '#6B8E23',
            data: data_scatter2
        }
    ]
};
// 图表初始化函数
const chart = Highcharts.chart('app', options);
      })();

    </script>
</body>
</html>
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console