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) #训练分类器