|

楼主 |
发表于 2020-5-19 13:46:46
|
显示全部楼层
- import pandas as pd
- import numpy as np
- import matplotlib.pyplot as plt
- import xlwt
- data = pd.read_excel(io='D:/人工智能/作业/Homework7.xlsx', sheet_name='In1Out1')
- data.insert(loc=1, column='x0', value=1) # 在每行数据的第二列添加x0=1
- x_train = data.iloc[:, 1:3].to_numpy() # 抽取第二三列的数据,转换成数组格式
- targets = data.iloc[:, 3].to_numpy() # 抽取第四列targets
- data1 = pd.read_excel(io='D:/人工智能/作业/Homework7.xlsx', sheet_name='Drawing_In1Out1')
-
- data1.insert(loc=1, column='x0', value=1)
- x_Drawing_In1Out1 = data1.iloc[:, 1:3].to_numpy()
- x1 = data1.iloc[1:,2].to_numpy()
- y1 = data1.iloc[1:,3].to_numpy()
- DeltaHid = 0.3
- DeltaOut = 0.001
- α = 0.1
- CCount = 0 # 初始化计数变量
- n = x_train.shape[0] # 得到提取数据的数量
- Max_iteration = int(input('Total Iteration:')) # 输入最大迭代次数
- Weight_In_Hid = np.random.normal(size=(2,2))
- Weight_Hid_Out = np.random.normal(size=(3,1))
- Weight_In_Hid_Delta =np.zeros((2,2))
- Weight_Hid_Out_Delta = np.zeros((3,1))
- for i in range(Max_iteration):
- for k in range(n):
- H = np.zeros([3])
-
- neth1 = np.dot(Weight_In_Hid[:,0],x_train[k])
- neth2 = np.dot(Weight_In_Hid[:,1],x_train[k])
- H[0] = 1.0
- H[1] = 1/(1+np.e**(-neth1))
- H[2] = 1/(1+np.e**(-neth2))
- # 确定输出层
-
- Y = np.dot(Weight_Hid_Out.T,H) # Y值
-
- Delta_Out = targets[k] - Y
-
- Delta_Hid = np.zeros((2,1))
- Delta_Hid[0] = Delta_Out * Weight_Hid_Out[1] * H[1] * (1-H[1])
- Delta_Hid[1] = Delta_Out * Weight_Hid_Out[2] * H[2] * (1-H[2])
- for a in range(3):
- Weight_Hid_Out_Delta[a] = α * Weight_Hid_Out_Delta[a] + DeltaOut * Delta_Out * H[a]
- for b in range(2):
- for j in range(1,3):
- Weight_In_Hid_Delta[b,j-1] = α * Weight_In_Hid_Delta[b,j-1] + DeltaHid * x_train[k,b]
- Weight_In_Hid = Weight_In_Hid + Weight_In_Hid_Delta
- Weight_Hid_Out = Weight_Hid_Out + Weight_Hid_Out_Delta
-
-
- CCount += 1 # 计数
- if CCount == n: # 当循环次数等于数据数时跳出循环进行下一次循环
- break
-
- print('Weight_In_Hid:')
- print(Weight_In_Hid)
- print('Weight_Hid_Out:')
- print(Weight_Hid_Out)
-
- for c in range(n):
-
- n_h1 = np.dot(Weight_In_Hid[:,0].T,x_Drawing_In1Out1[c])
- n_h2 = np.dot(Weight_In_Hid[:,1].T,x_Drawing_In1Out1[c])
-
- h0 = 1.0
- h1 = 1.0 / (1+np.exp(-n_h1))
- h2 = 1.0 / (1+np.exp(-n_h2))
- Draw_H = [h0,h1,h2]
- # 确定输出层
-
- Draw_Y = np.zeros([n])
- Draw_Y[c] = np.dot(Weight_Hid_Out.T[0],Draw_H)# Y值
- # 画图
- plt.ion()
- plt.cla() # 清空画布
- plt.ylim(-1, 4) # 固定y轴的取值范围
- plt.xlim(-10, 10) # 固定x轴的取值范围
- x = np.linspace(-10, 10, 8)
-
- plt.plot(x1,y1, color='red')
-
- plt.plot(x_Drawing_In1Out1[:,1],Draw_Y,color='blue')
-
- plt.pause(0.1) # 暂停一会
-
- plt.ioff() # 关闭交互
- plt.show()
复制代码 |
|