1. 程式人生 > >DL之perceptron:利用perceptron感知機對股票實現預測

DL之perceptron:利用perceptron感知機對股票實現預測

DL之perceptron:利用perceptron感知機對股票實現預測

import numpy as np
import operator
import os

# create a dataset which contains 3 samples with 2 classes
def createDataSet():
    # create a matrix: each row as a sample
    group = np.array([[20,2], [50,1], [10,3],[60,0.5]])
    labels = [1, -1, 1,-1] # four samples and two classes
    return group, labels

#classify using perceptron
def perceptronClassify(trainGroup,trainLabels):
    global w, b
    isFind = False  #the flag of find the best w and b
    numSamples = trainGroup.shape[0]    #計算矩陣的行數
    mLenth = trainGroup.shape[1]    #計算矩陣的列數
    w = [0]*mLenth  #初始化w
    b = 0   #初始化b
    while(not isFind):  #定義迭代計算w和b的迴圈
        for i in range(numSamples):
            if cal(trainGroup[i],trainLabels[i]) <= 0: #計算損失函式,y(wx+b)<=0時更新引數
                print (w,b)
                update(trainGroup[i],trainLabels[i]) #更新計算w和b
                break    #end for loop
            elif i == numSamples-1:
                print (w,b)
        isFind = True   #end while loop
        
def cal(row,trainLabel): #定義損失函式
    global w, b
    res = 0
    for i in range(len(row)):
        res += row[i] * w[i]
        res += b
        res *= trainLabel
    return res
def update(row,trainLabel): #學習率為1的更新計算
    global w, b
    for i in range(len(row)):
        w[i] += trainLabel * row[i]
        b += trainLabel

g,l =createDataSet()        #生成資料集
perceptronClassify(g,l)     #訓練分類器