Kiba518

Kiba518

三线城市架构师一枚。

Fork me on GitHub

没有Python基础,如何学习用Python写机器学习

前言

我是一个完全没用过python的人,所以,想写机器学习,就得从语法入手。

首先上W3cSchool去学习基础语法。

基础语法都差不多,重点看一下函数,模块,面向对象。

函数的写法稍有不同,格式上类似yml的写法;模块会介绍import的相关信息;面向对象会介绍类的相关信息。

参考网站:

https://www.w3cschool.cn/python3/
https://www.w3cschool.cn/python3/python3-eam72ylh.html

理论上,2~3个小时就能学完。

K-means机器学习

我这里使用VSCode进行开发,随便打开一个文件夹,然后创建一个KmeansTest.py的文件,然后点运行(右上角的三角),然后系统会提示安装python。

image

因为我电脑是Window11,所以会弹窗提示我安装python3的包,点击安装即可;如果不是window11,就自己下个python包,配置一下环境变量,这个过程不复杂。

然后,因为我是完全没有python经验的,所以我也不知道要安装什么插件,所以我就打开扩展窗口,输入python搜索,随便按几个最上面的插件。

image

然后,先在终端里执行下面代码:

 pip install scikit-learn
 pip install matplotlib

scikit-learn是做机器学习的,matplotlib是一个绘图的库。

然后我们定义个数组做为学习的源数据.

X1 = [
 [0.0,0.0],
 [0.0,0.3],
 [0.3,0.0],
 [9.0,0.0],
 [9.0,0.6],
 [9.6,0.0]]

然后编写代码:

from sklearn.cluster import KMeans
# 按F2可以重命名
xList = [
 [0.0,0.0],
 [0.0,0.3],
 [0.3,0.0],
 [9.0,0.0],
 [9.0,0.6],
 [9.6,0.0]]
n_clusters = 2
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(xList)

xLable = cluster.labels_ 
# xlable 是上面那个集合,每个元素的所属分组
print ("xLable",xLable)

xListGroup1 =[]
xListGroup2 =[]
# 使用range时,循环的是索引,python里叫序列
for index in range(len(xList)) :
   
    cluster = xLable[index]
    if(cluster==1):
        xListGroup1.append( xList[index])
    if(cluster==0):
        xListGroup2.append( xList[index])
    
 
print ("xListGroup1",xListGroup1)
print ("xListGroup2",xListGroup2)

调试得到结果:

如我们期待的一样,前3个数据比较接近,后三个比较接近,所以,分两组的话,就是前3个一组,后3个一组。

经验

调试时,删除终端再建一个,不然有时候会出现莫名奇妙的异常,而实际上,代码并没有错误,这个非常耽误时间。
image

使用matplotlib

使用matplotlib的make_blobs函数,生成一个大一点的数据源测试,代码如下:

from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

xList, y = make_blobs(n_samples=500,n_features=2,centers=4,random_state=1)

n_clusters = 2
cluster = KMeans(n_clusters=n_clusters, random_state=0).fit(xList)

xLable = cluster.labels_ 
# xlable 是上面那个集合,每个元素的所属分组
print ("xLable",xLable)

xListGroup1 =[]
xListGroup2 =[]

# 使用range时,循环的是索引,python里叫序列
for index in range(len(xList)) :
    cluster = xLable[index]
    if(cluster==1):
        xListGroup1.append( xList[index])
    if(cluster==0):
        xListGroup2.append( xList[index])

print ("xListGroup1",xListGroup1)
print ("xListGroup2",xListGroup2)

结语

通过上面代码,我们简简单单的实现了一个机器学习。

如果想让这个功能跟项目沟通,那就学习一下网络编程,写一个http监听,然后接一组数据,用上面代码处理完,返回一组数据即可。

同理,上面的代码可以换成opencv的,可以换成TensorFlow的。


注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!



若您觉得这篇文章还不错,请点击下方的【推荐】,非常感谢!

https://www.cnblogs.com/kiba/p/18098264

posted @ 2024-03-27 10:31  kiba518  阅读(273)  评论(0编辑  收藏  举报