美文网首页
机器学习 入门

机器学习 入门

作者: 小葫芦lu | 来源:发表于2017-12-12 11:29 被阅读52次
File "sklearn/svm/libsvm_sparse.pyx", line 5, in init sklearn.svm.libsvm_sparse (sklearn/svm/libsvm_sparse.c:7615)
ImportError: cannot import name ConvergenceWarning

报错处理

sudo pip uninstall scikit-learn
sudo pip install scikit-learn
机器学习SVM分类器
  1. 使用sklearn进行分类、预测
from sklearn import svm

X = [[0, 0], [1, 1], [1, 0]]#取样
y = [0, 1, 1]#

#分类
clf = svm.SVC()
clf.fit(X, y)#训练
result = clf.predict([[2, 2]])
print clf
print result

# 预测
clt = svm.SVR()
clt.fit(X, y)
result = clt.predict([[2, 2]])
print result

输出及注解

"""
输出
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
  decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
  max_iter=-1, probability=False, random_state=None, shrinking=True,
  tol=0.001, verbose=False)
[1]
[ 0.70393476]
//[1]  (将训练数据分类为y=1)

SVC参数解释
(1)C: 目标函数的惩罚系数C,用来平衡分类间隔margin和错分样本的,default C = 1.0。C越大,相当于惩罚松弛变量,希望松弛变量接近0,即对误分类的惩罚增大,趋向于对训练集全分对的情况,这样对训练集测试时准确率很高,但泛化能力弱。C值小,对误分类的惩罚减小,允许容错,将他们当成噪声点,泛化能力较强。;
(2)cache_size: 核函数cache缓存大小,默认为200;
(3)class_weight: 类别的权重,字典形式传递。设置第几类的参数C为weight*C(C-SVC中的C);
(4)coef0:核函数中的常数项,'RBF' and 'Poly'有效;
(5)decision_function_shape : ‘ovo’ 一对一, ‘ovr’ 多对多  or None 无, default=None
(6)degree:多项式poly函数的维度,默认是3,选择其他核函数时会被忽略;
(7)gamma:核函数的系数('Poly', 'RBF' and 'Sigmoid'), 默认是gamma = 1 / n_features;
(8)kernel:核函数,默认是rbf,可以是‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’, ‘precomputed’
    0 – 线性:u'v
    1 – 多项式:(gamma*u'*v + coef0)^degree
    2 – RBF函数:exp(-gamma|u-v|^2)
    3 –sigmoid:tanh(gamma*u'*v + coef0)
(9)max_iter: 最大迭代次数,default = 1, if max_iter = -1, no limited,无限次;
(10)probablity: 可能性估计是否使用(true or false);
(11)random_state :用于概率估计的数据重排时的伪随机数生成器的种子。
(12)shrinking:是否进行启发式;
(13)tol(default = 1e - 3): svm结束标准的精度;
(14)verbose: 允许冗余输出;

SVM: Support Vector Machines(支持向量机),可以用来做分类和回归。
SVC是SVM的一种Type,是用来的做分类的,SVR是SVM的另一种Type,是用来的做回归的。
"""
  1. 使用numpy
from numpy import *
a = matrix([ [1, 2], [3, 4] ])
print a
# 科学计算

import numpy as np
print np.version.version # 获取当前numpy版本

a = np.array([1, 2, 3, 4])
b = np.array([1.0, 2, 3, 4])
print a, b

# 二维数组 以list 或 元组为元素
x = np.array( ((1, 2, 3), (4, 5, 6)) )
print x

y = np.array( [[1, 2, 3], [4, 5, 6]] )
print y

# 数据类型设定与转换
# numpy ndarray数据类型可以通过参数dtype 设定,而且可以使用astype转换类型,在处理文件时候这个会很实用,注意astype 调用会返回一个新的数组,也就是原始数据的一份拷贝。
num_str = np.array(['1.2', '2', '4.5'], dtype=np.string_) # 从字符串拷贝
num_str = num_str.astype(float) # 设置新的类型 float64,  int (需要array对应为整型)
print num_str
# 索引(index)、切片(slicing)
x = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
print x
print x[1, 2]
y = x[:, 1]
print y
y[0] = 10
print y
print x # 以上操作改变了x[0, 1]的值,所以由此获取的数组值改变,则原数组随之改变,为同一内存空间

# 获取不影响原数组的副本
arr_copy = x[1:3].copy()
arr_copy[0] = 24 # 第0行为24
arr_copy[:, 1] = 36 # 第1列为36
print arr_copy

# 切片
sl = range(10)
print sl
t1 = sl[4: 8]
t1[0] = 22
print t1

arr2d = np.arange(1, 10).reshape(3, 3) #将一维数组转换为二维数组
print arr2d
print arr2d[2]
print arr2d[0][1]

print arr2d==1 # 返回一个对应的二维数组,值为分别判断的结果
"""
[[ True False False]
 [False False False]
 [False False False]]
"""
data = np.array([[ 0.36762706, -1.55668952,  0.84316735, -0.116842],
       [ 1.34023966,  1.12766186,  1.12507441, -0.68689309],
       [ 1.27392366, -0.43399617, -0.80444728,  1.60731881],
       [ 0.23361565,  1.38772715,  0.69129479, -1.19228023],
       [ 0.51353082,  0.17696698, -0.06753478,  0.80448168],
       [ 0.21773096,  0.60582802, -0.46446071,  0.83131122],
       [ 0.50569072,  0.04431685, -0.69358155, -0.9629124 ]])
data[data < 0] = 0 # 将小于0的值全部替换为0
print data
"""
[[ 0.36762706  0.          0.84316735  0.        ]
 [ 1.34023966  1.12766186  1.12507441  0.        ]
 [ 1.27392366  0.          0.          1.60731881]
 [ 0.23361565  1.38772715  0.69129479  0.        ]
 [ 0.51353082  0.17696698  0.          0.80448168]
 [ 0.21773096  0.60582802  0.          0.83131122]
 [ 0.50569072  0.04431685  0.          0.        ]]
"""

# 数组文件输入、输出
# 数组以二进制格式保存到磁盘,np.save、np.load读写函数,默认情况下,数组以未压缩的原始二进制格式存储在.npy文件中
arr = np.arange(10)
np.save('some_array', arr) #存储

tt = np.load('some_array.npy') # 读取
print tt

arr = np.arange(1, 10).reshape(3, 3)
# np.savetxt('data1.txt', arr)
np.savetxt('data1.txt', arr, fmt='%d', delimiter=',')

# ac = np.loadtxt('data1.txt')
ac = np.loadtxt('data1.txt', dtype=int, delimiter=',')# 读取要与写入参数一致
print 'ac', ac

"""
1. 1.47368421 1.94736842 2.42105263 2.89473684
3.36842105 3.84210526 4.31578947 4.78947368 5.26315789
5.73684211 6.21052632 6.68421053 7.15789474 7.63157895
8.10526316 8.57894737 9.05263158 9.52631579 10.
"""
ad = np.loadtxt('data.txt', dtype=float, delimiter=' ')
print ad

# 构造矩阵
ma1 = np.arange(15).reshape(3, 5) # 先获取一个0到15的数组,之后变形为3行5列的二维数组
"""
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
"""
ma2 = np.linspace(1, 10, 20) # 从1 到 10, 随机出20个数
"""
[  1.           1.47368421   1.94736842   2.42105263   2.89473684
   3.36842105   3.84210526   4.31578947   4.78947368   5.26315789
   5.73684211   6.21052632   6.68421053   7.15789474   7.63157895
   8.10526316   8.57894737   9.05263158   9.52631579  10.        ]
"""
ma3 = np.zeros((3, 4)) # 获得一个 3行 4列的 二维数组,元素均为0.
"""
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
"""
ma4 = np.ones((3, 4)) # 获得一个 3行 4列的 二维数组,元素均为1.
"""
[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]
"""
ma5 = np.eye(3) # 获得一个3行3列的矩阵,n行n列的元素均为1.,其他均为0.
"""
[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 0.  0.  1.]]
"""
print ma5

# 数组属性
print 'ndim 维数', ma4.ndim # 维数
print 'shape 数组每一维的大小', ma4.shape # 数组每一维的大小
print 'size 元素个数', ma4.size # 元素个数
print 'dtype 元素类型', ma4.dtype # 元素类型
print 'itemsize 每个元素所占的字节数', ma4.itemsize # 每个元素所占的字节数
print ma4.flags # 数组信息
print ma4.data # Python buffer object pointing to the start of the array’s data.
print ma4.strides # Tuple of bytes to step in each dimension when traversing an array.
print ma4.base # Total bytes consumed by the elements of the array.
print ma4.nbytes # Base object if memory is from some other object.
"""
ndim 维数 2
shape 数组每一维的大小 (3, 4)
size 元素个数 12
dtype 元素类型 float64
itemsize 每个元素所占的字节数 8
  C_CONTIGUOUS : True
  F_CONTIGUOUS : False
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
�?�?�?�?�?�?�?�?�?�?�?�?
(32, 8)
None
96
"""

# 合并数组 (相当于连接)
# vstack(垂直方向),hstack(水平方向)
aa = np.ones((2, 2))
bb = np.eye(2)
print 'aa =\n', aa
print 'bb = \n', bb
print 'v =\n', np.vstack((aa, bb))
print 'h =\n', np.hstack((aa, bb))
"""
aa =
[[ 1.  1.]
 [ 1.  1.]]
bb =
[[ 1.  0.]
 [ 0.  1.]]
v =
[[ 1.  1.]
 [ 1.  1.]
 [ 1.  0.]
 [ 0.  1.]]
h =
[[ 1.  1.  1.  0.]
 [ 1.  1.  0.  1.]]
"""

# 矩阵运算 转置
t = np.array([[1, 0], [2, 3]])
print 't =\n', t
print '转置\n', t.transpose()
"""
t =
[[1 0]
 [2 3]]
转置
[[1 2]
 [0 3]]
"""
# 特征值特征向量
from numpy import linalg as nplg
print '求此矩阵的特征值与特征向量\n', t
w, v = nplg.eig(t)
print w # 特征值
print v #特征向量
"""
求此矩阵的特征值与特征向量
[[1 0]
 [2 3]]
[ 3.  1.]
[[ 0.          0.70710678]
 [ 1.         -0.70710678]]
"""
# 数组



  1. 中文分词
# 中文分词
import jieba
seg_list = jieba.cut("北京野生动物园轿车遭黑熊围堵")
print "Default Mode:", ' '.join(seg_list)
  1. 简单绘图
import matplotlib.pyplot as plt

labels = 'frogs', 'hogs', 'dogs', 'logs'
sizes = 15, 20, 45, 10
colors = 'yellowgreen', 'gold', 'lightskyblue', 'lightcoral'
explode = 0, 0.1, 0, 0
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=50)
plt.axis('equal')
plt.show()

如果无法运行,使用pip重新安装matplotlib,如果出现无权限的情况,在mac系统下,重启进入恢复模式下,右上角终端,输入csrutil disable,关闭SIP保护。重新启用,则使用csrutil enable即可。


image.png
  1. pandas



机器学习

  1. Theano
    Theano是我们关注的第一个 Python 深度学习库

  2. Caffe
    Caffe 是一个深度学习框架
    用 Caffe 实现 Google 的 #DeepDream

  3. Nightmare

相关文章

网友评论

      本文标题:机器学习 入门

      本文链接:https://www.haomeiwen.com/subject/wypgixtx.html