机器学习-感知机

# 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()


#机器学习#
全部评论
来自学霸的分享,强🎉
点赞 回复 分享
发布于 2022-08-31 16:57 陕西

相关推荐

uu们,拒offer时hr很生气怎么办我哭死
爱睡觉的冰箱哥:人家回收你的offer,或者oc后没给你发offer的时候可不会愧疚你,所以你拒了也没必要愧疚他。
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务