机器学习-感知机
# In[1]:
# 导入模块
import numpy as np
import matplotlib.pyplot as plt
# In[2]:
# 导入数据
train = np.loadtxt('/Users/sugunren/Desktop/images1.csv', delimiter=',', skiprows=1)
x_train, y_train = train[:,0:2], train[:,2]
# In[3]:
# 画图
plt.plot(x_train[y_train == 1, 0], x_train[y_train == 1, 1], 'o')
plt.plot(x_train[y_train == -1, 0], x_train[y_train == -1, 1], 'x')
plt.show()
# In[4]:
# 权重初始化
w = np.random.rand(2)
# In[5]:
# 判断函数
def f(x):
if np.dot(w,x) >= 0:
return 1
else:
return -1
# In[6]:
# 重复次数
epoch = 100
# In[7]:
# 更新次数
count = 0
# In[8]:
# 学习权重
for _ in range(epoch):
for x, y in zip(x_train, y_train):
if f(x) != y:
w += y*x
count += 1
print('第{}次:w = {}'.format(count,w))
# In[9]:
# 绘图
x1 = np.arange(0, 500)
plt.plot(x_train[y_train == 1, 0], x_train[y_train == 1, 1], 'o')
plt.plot(x_train[y_train == -1, 0], x_train[y_train == -1, 1], 'x')
plt.plot(x1, -w[0]/w[1] * x1, linestyle = 'dashed')
plt.show()
#机器学习#

查看2道真题和解析

