99 lines
3.4 KiB
Python
99 lines
3.4 KiB
Python
import numpy as np
|
||
import matplotlib.pyplot as plt
|
||
import pandas as pd
|
||
import matplotlib
|
||
|
||
class lab6:
|
||
|
||
def __init__(self):
|
||
pass
|
||
|
||
def main(self):
|
||
|
||
matplotlib.use('TkAgg')
|
||
|
||
#создание массивов
|
||
g1 = [[0.7, 0.3, 1.2],
|
||
[0.5, 0.7, 1.0],
|
||
[0.4, 1.0, 0.4],
|
||
[0.7, 0.7, 1.0],
|
||
[0.6, 0.6, 1.5],
|
||
[0.6, 0.6, 1.2],
|
||
[0.6, 0.5, 1.0],
|
||
[0.4, 0.9, 0.6],
|
||
[0.5, 0.6, 1.1],
|
||
[0.8, 0.3, 1.2]]
|
||
g2 = [[0.4, 0.2, 0.8],
|
||
[0.2, 0.2, 0.7],
|
||
[0.9, 0.3, 0.5],
|
||
[0.8, 0.3, 0.6],
|
||
[0.5, 0.6, 0.4],
|
||
[0.6, 0.5, 0.7],
|
||
[0.4, 0.4, 1.2],
|
||
[0.6, 0.3, 1.0],
|
||
[0.3, 0.2, 0.6],
|
||
[0.5, 0.5, 0.8]]
|
||
# Создание датафреймов
|
||
df_g1 = pd.DataFrame(g1, columns=['X1', 'Y1', 'Z1'])
|
||
df_g2 = pd.DataFrame(g2, columns=['X2', 'Y2', 'Z2'])
|
||
# Объединение датафреймов
|
||
df = pd.concat([df_g1, df_g2], axis=1)
|
||
# п3: построение скаттерограммы
|
||
fig = plt.figure()
|
||
ax = fig.add_subplot(111, projection='3d')
|
||
# Наносим точки на график
|
||
ax.scatter(df.iloc[:, 0],
|
||
df.iloc[:, 1],
|
||
df.iloc[:, 2],
|
||
color='midnightblue')
|
||
ax.scatter(df.iloc[:, 3],
|
||
df.iloc[:, 4],
|
||
df.iloc[:, 5],
|
||
color='darkred')
|
||
ax.set_xlabel('1 признак')
|
||
ax.set_ylabel('2 признак')
|
||
ax.set_zlabel('3 признак')
|
||
plt.legend(['g1', 'g2'])
|
||
plt.show()
|
||
|
||
# п2: последовательное обучение с коррекцией ошибки
|
||
one = np.ones((10, 1))
|
||
g1 = np.hstack((g1, one))
|
||
g2 = np.hstack((g2, one))
|
||
g2 = (-1)*np.array(g2)
|
||
g = np.vstack((g1, g2))
|
||
W = np.mean(g1, axis=0) - np.mean(g2, axis=0)
|
||
w = W/np.linalg.norm(W)
|
||
proj1=np.matmul(g,w)
|
||
print (proj1)
|
||
plt.figure(3)
|
||
plt.subplot(1, 2, 1)
|
||
plt.hist(proj1.T[0:9], bins= 10,color = ('firebrick'), alpha=0.7, edgecolor = 'black',label='g1')
|
||
plt.hist((-1)*proj1.T[10:19], bins= 10,color = ('indigo'), alpha=0.7, edgecolor ='black',label='g2')
|
||
plt.legend()
|
||
plt.xlabel('Значение')
|
||
plt.ylabel('Количество')
|
||
plt.title('Гистограмма первого приближения')
|
||
learn_coeff = 0.1
|
||
while min(proj1)<0:
|
||
for ind, data_sample in enumerate(g):
|
||
proj1[ind] = np.matmul(data_sample, w)
|
||
if proj1[ind]<0:
|
||
w = w + data_sample*learn_coeff
|
||
proj = np.matmul(g, w)
|
||
v1 = np.matmul(g, w)
|
||
# Построение гистограммы проекций
|
||
plt.subplot(1, 2, 2)
|
||
plt.hist(v1.T[0:9], bins= 10,color = ('firebrick'), alpha=0.7, edgecolor = 'black',label='g1')
|
||
plt.hist((-1)*v1.T[10:19], bins= 10,color = ('indigo'), alpha=0.7, edgecolor ='black',label='g2')
|
||
plt.xlabel('Значение')
|
||
plt.ylabel('Количество')
|
||
plt.title('Гистограмма после обучения')
|
||
plt.legend()
|
||
plt.show()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
l6 = lab6()
|
||
l6.main()
|