神经网络入门(python 自建)

风流意气都作罢 提交于 2019-12-22 20:23:02

训练得到θ

import numpy as np
import pandas as pd
from keras.datasets import  mnist

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def top(x,y,o):
    z=x.dot(o)
    h=sigmoid(z)
    j=np.sum(y*np.log(h)+(1-y)*np.log(1-h))
    return x,y,h,o,j # h 为预测,j 为代价函数

def bottom(x,y,h,o,j):
    s=h-y
    o=o-(1/x.shape[0])*(x.T).dot(s)
    return o # o 为修正后的参数

def begin(x,y):
    o=np.zeros((x.shape[1], y.shape[1]))
    return x,y,o


# 数据准备
# x =
# x1
# x2
# x3
#
# y =
# y1
# y2
# y3

(train_data, train_labels), (test_data, test_labels) = mnist.load_data()

x=train_data.reshape(60000,784)
y=np.zeros((60000,10))
for i in range(train_labels.shape[0]):
    y[i,train_labels[i]]=1


# 调用网络,该网络只有输入输出层
b=begin(x,y)
t=top(b[0],b[1],b[2])
o=bottom(t[0],t[1],t[2],t[3],t[4])
for i in range(9):
    t = top(x, y, o)
    o=bottom(t[0],t[1],t[2],t[3],t[4])
    print(o) # 在控制台显示

# 写入到csv文件,追加的形式
pd.DataFrame(o).to_csv('D:\PyCharm_test\\bp\\test.csv', header=False,index=None)

带入θ测试

import pandas as pd
import numpy as np
from keras.datasets import  mnist

(train_data, train_labels), (test_data, test_labels) = mnist.load_data()
o=np.array(pd.read_csv('D:\PyCharm_test\\bp\\test.csv',header=None))

def sigmoid(x):
    return 1 / (1 + np.exp(-x))


# print(test_data.shape)
x=test_data.reshape(10000,784)
for i in range(x.shape[0]):
    y=sigmoid(x[i].dot(o))
    print(test_labels[i])
    print(x[i].dot(o))
    print(y)
    pd.DataFrame(y).to_csv('D:\PyCharm_test\\bp\\testy.csv', mode='a+',header=False,index=None)
    

结论

精确度不高,两层网络,比较简易,且省去了θ0.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!