机器学习&深度学习实践(python版)系列----Linear Regression(线性回归)

    今天和一位师兄决定复习一下Andrew Ng的机器学习和深度学习教程理论知识,用Python实现教程中的练习。教程分为:

机器学习:http://openclassroom.stanford.edu/MainFolder/CoursePage.php?course=MachineLearning

深度学习:http://ufldl.stanford.edu/wiki/index.php/UFLDL%E6%95%99%E7%A8%8B(中文版)

    我们决定从机器学习开始,逐渐实现。

    写这个系列主要是方便以后学习,也是对前期学习的一个总结。欢迎大家共同讨论!

今天是第一篇:线性回归

1、理论

教程链接:http://openclassroom.stanford.edu/MainFolder/DocumentPage.php?course=MachineLearning&doc=exercises/ex2/ex2.html

具体理论就不细讲了,大家可以看教程,在这里粘贴几个重要的公式:

机器学习&深度学习实践(python版)系列----Linear Regression(线性回归)_第1张图片

注意:里面的学习率设定为0.07

2、代码(python)

# -*- coding: utf-8 -*-
"""
Created on Fri Dec 11 09:55:23 2015

@author: Administrator
"""

import matplotlib.pyplot as plt
import sys
import numpy as np
"""
#加载数据
def load(file_name):
    data=[]
    try:
        file_txt=open(file_name,"r")
    except IOError:
        print >> sys.stderr, "File could not be opened"
        sys.exit(1)
    lines = file_txt.readlines()
    for line in lines:
        cur_line = line.strip().split('\n')
        data.append('%f4'%float(cur_line[0]))
        #data.append(cur_line)
    data1 = np.array(data)
    file_txt.close()
    return data1
"""
#加载数据
def load_data(data_name):
    dataMat = []
    fr = open(data_name)
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0,float(lineArr[0])])#在第一列加上1.0
    return dataMat
    
#加载标签
def load_label(label_name):
    labelMat = []
    fr = open(label_name)
    for line in fr.readlines():
        lineArr = line.strip().split()
        labelMat.append(float(lineArr[0]))
    return labelMat
    
    
if __name__ == "__main__":
    x = load_data(r'ex2x.dat')
    #print x
    y = load_label(r'ex2y.dat')
    """
    plt.figure(figsize=(5,4))
    plt.xlabel(r'Age in years')
    plt.ylabel(r'Height in meters')
    plt.title(r'Linear Regression')
    plt.plot(x[1:50][1],y,'o')打印图,在此不打印了
    """
    x = np.mat(x)#用np.mat转换成矩阵
    y = np.mat(y).transpose()#将标签转置
    m,n = np.shape(x)#获得矩阵行,列数
    lr = 0.07
    theat = np.mat(np.zeros(n))
    for i in range(1000):#迭代次数可以设置的大些
        h = np.dot(x,theat.transpose())
        det_h = h-y
        det_t = lr*(1.0/m)*np.dot(det_h.transpose(),x)
        theat = theat-det_t
        print theat
3、问题集锦

     由于是第一次用python编写机器学习的相关代码,因此遇到了很多问题,尤其是有关矩阵的操作,在这里和大家分享,但是我没有按照问题出现的顺序书写,顺序有点乱!

(1)TypeError: unsupported operand type(s) for *: 'builtin_function_or_method' and 'float'

解决方式:http://c.360webcache.com/c?m=bbe3fc3f97a476de966c280733f0a91b&q=TypeError%3A+unsupported+operand+type%28s%29+for+%2A%3A+%27builtin_function_or_method%27+and+%27float%27&u=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F30327115%2Ftypeerror-unsupported-operand-types-for-float-and-builtin-function-or-m%2F30327327

      这个问题的出现主要是在矩阵转置的时候用transpose函数时没有加上括号,如treat.transpose是错误的,treat.transpose()正确!

(2)UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5 in position 108: ordinal not in range

错误分析:

def load_data(data_name):
    dataMat = []
    fr = open(data_name)
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0,float(lineArr[0])])#在第一列加上1.0
    return dataMat

错误发生在下面一句,因为lineArr是个list,float(lineArr)是错误的
dataMat.append([1.0,float(lineArr[0])])#在第一列加上1.0
float()将字符串转换成浮点型,但是不能讲一个列表转换成浮点型,因此必须加上一个[0],指定将哪个元素转换成浮点型。在将字符串转换成浮点型时,如果我们想指定转换后的位数可以使用

a = '%nf'%float(str)

n就是位数。

参考链接:http://bbs.chinaunix.net/thread-2318251-1-1.html

(3)Python main函数

使用python最不习惯的一点就是不用写主函数程序就能运行。但是有一个主函数,无论是读程序还是调试程序,对我们都有帮助,其实我们可以用下面的语句定义个主函数(注意格式

if __name__=="__main__":
小实例:

<span style="font-size:18px;">#hello.py
def foo():
    str="function"
    print(str);
if __name__=="__main__":
    print("main")
    foo()</span>
参考链接:http://blog.sina.com.cn/s/blog_71a7f0870100wndd.html

(4)读取*****.dat文件

开始以为读取这个类型的文件需要自己写个函数,后来发现,读取这个类型的文件与读取****.txt文件没有什么区别。

<span style="font-size:18px;">import sys
try:
    file=open("client.dat","w")
except IOError,message:
    print >> sys.stderr, "File could not be opened",message
    sys.exit(1)
print "Enter the accout,name and age."
while 1:
    try:
        accountline=raw_input("?")
    except EOFError:
        break
    else:
        print >>file,accountline
file.close()</span>
参考链接:http://blog.chinaunix.net/uid-7581503-id-2048769.html

(5)list(列表)转换成mat(矩阵)

    python中使用的最多的是list,mat反而用的很少,但是一些理论推导中用的都是矩阵,所以干脆我把list转成了mat类型。

x = np.mat(x)#将list转换成mat
y = np.mat(y).transpose()#将标签转置
m,n = np.shape(x)#获得矩阵行,列数
theat = np.mat(np.zeros(n))#创建一个元素为0的矩阵
(6)矩阵乘法

python中计算两个矩阵的点乘用np.dot(mat1,mat2)函数

<span style="font-size:18px;">h = np.dot(x,theat.transpose())</span>



你可能感兴趣的:(机器学习&深度学习实践(python版)系列----Linear Regression(线性回归))