春节想学习一些人工智能方面的知识,跟上时代,云风去年推荐了入门的鱼书:深度学习入门:基于Python的理论与实现
图灵社区图灵社区成立于2005年6月,以策划出版高质量的科技书籍为核心业务,主要出版领域包括计算机、电子电气、数学统计、科普等,通过引进国际高水平的教材、专著,以及发掘国内优秀原创作品等途径,为目标读者提供一流的内容。https://www.ituring.com.cn/book/1921这本书读起来没有门槛,初五不串门,在家安心读了第一章:Python入门,记录如下
安装python:
第一章 python入门
https://www.7-zip.org/download.html
https://www.ituring.com.cn/book/1921
install python3:Anaconda发行版
https://www.anaconda.com/download
powershell
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
C:\python\ml> python --version
Python 3.11.5
(base) PS C:\python\ml> python
Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
2024.04.28 这个anaconda竟然有版权问题,看介绍是免费下载的。所以我把windows的卸载了。
在linux下重新安装了一套,似乎没有说有这类问题:
machinelearning]$ python --version
Python 3.11.5
machinelearning]$ python
Python 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
并未显示Anaconda信息。
确认安装了anaconda版本。下面就开始做书上的实验了
不安装anaconda,也可以直接用python.
win11:microsoft store里面可以直接安装python
ch01> python --version
Python 3.12.4
安装numpy
C:\python> pip install numpy
Successfully installed numpy-1.26.4
python -m pip install -U pip
python -m pip install -U matplotlib
对话模式:
1.3.1 算术运算
(base) [machinelearning]$ python
Python 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 1+2
3
>>> 1-2
-1
>>> 4*5
20
>>> 7/5
1.4
>>> 3**2
9
>>>
** 表示乘方(3**2 是 3 的 2 次方)
在 Python 2.x 中,整数除以整数的结果是整数,比如,7 ÷ 5 的结果是 1。但在 Python 3.x 中,整数除以整数的结果是小数(浮点数)
1.3.2 数据类型
>>> type(10)
<class 'int'>
>>> type(2.716)
<class 'float'>
>>> type("hello")
<class 'str'>
>>>
1.3.3 变量
>>> x=10
>>> print(x)
10
>>> x=100
>>> print(x)
100
>>> y=3.14
>>> x*y
314.0
>>> type(x*y)
<class 'float'>
>>>
Python 是属于“动态类型语言”的编程语言,所谓动态,是指变量的类型是根据情况自动决定的
1.3.4 列表
>>> a=[1,2,3,4,5]
>>> print(a)
[1, 2, 3, 4, 5]
>>> len(a)
5
>>> a[1]
2
>>> a[0]
1
>>> a[4]
5
>>> a[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> a[4]=99
>>> print(a)
[1, 2, 3, 4, 99]
使用切片不仅可以访问某个值,还可以访问列表的子列表
>>> print(a)
[1, 2, 3, 4, 99]
>>> a[0:2]
[1, 2]
>>> a[1:]
[2, 3, 4, 99]
>>> a[:3]
[1, 2, 3]
>>> a[:-1]
[1, 2, 3, 4]
>>> a[:-2]
[1, 2, 3]
1.3.5 字典
>>> me={'height':180}
>>> me['height']
180
>>> me['weight']=70
>>> print(me)
{'height': 180, 'weight': 70}
1.3.6 布尔型
>>> hungry=True
>>> sleepy=False
>>> type(hungry)
<class 'bool'>
>>> not hungry
False
>>> hungry and sleepy
False
>>> hungry or sleepy
True
1.3.7 if 语句
>>> hungry=True
>>> if hungry:
... print("I'm hungry")
File "<stdin>", line 2
print("I'm hungry")
^
IndentationError: expected an indented block after 'if' statement on line 1
>>> print("I'm hungry")
File "<stdin>", line 1
print("I'm hungry")
IndentationError: unexpected indent
>>> if hungry:
... print("i'm hungry")
...
i'm hungry
>>> hungry=False
>>> if hungry:
... print("hungry")
... else:
... print("im not hungry")
... print("im sleepy")
...
im not hungry
im sleepy
上面的 if 语句中,if hungry: 下面的语句开头有 4 个空白字符。它是缩进的意思,表示当前面的条件(if hungry )成立时,此处的代码会被执行。这个缩进也可以用 tab 表示,Python 中推荐使用空白字符。
Python 使用空白字符表示缩进。一般而言,每缩进一次,使用 4 个空白字符。
1.3.8 for 语句
>>> for i in [1,2,3]:
... print(i)
...
1
2
3
1.3.9 函数
>>> def hello():
... print("Hello World!")
...
>>> hello()
Hello World!
>>>
>>>
>>>
>>> def hello(object)
File "<stdin>", line 1
def hello(object)
^
SyntaxError: expected ':'
>>> def hello(object):
... print("Hello"+object+"!")
...
>>> hello("cat")
Hellocat!
>>>
(base) [machinelearning]$
关闭 Python 解释器时,Linux 或 Mac OS X 的情况下输入Ctrl-D(按住 Ctrl,再按 D 键);Windows 的情况下输入Ctrl-Z,然后按 Enter 键。
1.4 Python脚本文件
1.4.1 保存为文件
(base) PS C:\python\ml\ch01> python hungry.py
I'm hungry!
linux环境
(base) [machinelearning]$ pwd
/media/vdc/book/booknotes/machinelearning
(base) [machinelearning]$ ls
(base) [machinelearning]$ mkdir ch01
(base) [machinelearning]$ cd ch01
(base) [ch01]$ touch hungry.py
(base) [ch01]$ vi hungry.py
(base) [ch01]$ python hungry.py
I'm hungry!
(base) [ch01]$
1.4.2 类
(base) PS C:\python\ml\ch01> python man.py
Initialized!
Hello David!
Good-bye David!
python中使用class关键字来定义类,累遵循如下格式:
class 类名:
def __init__(self,参数):#构造函数
...
def 方法1(self,参数):
...
这里有一个特殊的 init 方法,这是进行初始化的方法,也称为构造函数 (constructor)
在方法的第一个参数中明确地写入表示自身(自身的实例)的 self 是 Python 的一个特点
linux下的例子:
ch01]$ touch man.py
(base) ch01]$ vi man.py
(base) ch01]$ python man.py
Traceback (most recent call last):
File "/media/vdc/book/booknotes/machinelearning/ch01/man.py", line 1, in <module>
class Man:
File "/media/vdc/book/booknotes/machinelearning/ch01/man.py", line 9, in Man
m = Man("David")
^^^
NameError: name 'Man' is not defined. Did you mean: 'max'?
(base) [ch01]$ cat man.py
class Man:
def __init__(self, name):
self.name=name
print("Initialized!")
def hello(self):
print("Hello "+self.name+"!")
def goodbye(self):
print("Good-bye "+self.name+"!")
m = Man("David")
m.hello()
m.goodbye()
从程序看,是调用Man不需要空格,否则就是在class Man定义中了,所以找不到Man,去掉空格:
(base) [ch01]$ vi man.py
(base) [ch01]$ python man.py
Initialized!
Hello David!
Good-bye David!
1.5 NumPy
1.5.1 导入 NumPy
1.5.2 生成 NumPy 数组
>>> import numpy as np
>>> x=np.array([1.0,2.0,3.0])
>>> print(x)
[1. 2. 3.]
>>> type(x)
<class 'numpy.ndarray'>
1.5.3 NumPy 的算术运算
>>> x=np.array([1.0,2.0,3.0])
>>> y=np.array([2.0,4.0,6.0])
>>> x+y
array([3., 6., 9.])
>>> x-y
array([-1., -2., -3.])
>>> x*y
array([ 2., 8., 18.])
>>> x/y
array([0.5, 0.5, 0.5])
>>> x/2.0
array([0.5, 1. , 1.5])
NumPy 数组不仅可以进行 element-wise 运算,也可以和单一的数值(标量)组合起来进行运算。此时,需要在 NumPy 数组的各个元素和标量之间进行运算。这个功能也被称为广播
1.5.4 NumPy 的 N 维数组
>>> A=np.array([[1,2],[3,4]])
>>> print(A)
[[1 2]
[3 4]]
>>> A.shape
(2, 2)
>>> A.dtype
dtype('int64')
>>> B=np.array([[3,0],[0,6]])
>>> A+B
array([[ 4, 2],
[ 3, 10]])
>>> A*B
array([[ 3, 0],
[ 0, 24]])
NumPy 数组(np.array )可以生成 N 维数组,即可以生成一维数组、二维数组、三维数组等任意维数的数组。数学上将一维数组称为向量 ,将二维数组称为矩阵 。另外,可以将一般化之后的向量或矩阵等统称为张量 (tensor)
1.5.5 广播
>>> print(A)
[[1 2]
[3 4]]
>>> A*10
array([[10, 20],
[30, 40]])
>>> print(A)
[[1 2]
[3 4]]
>>> B=np.array([10,20])
>>> A*B
array([[10, 40],
[30, 80]])
在这个运算中,如图 1-2 所示,一维数组 B 被“巧妙地”变成了和二位数组 A 相同的形状,然后再以对应元素的方式进行运算。
1.5.6 访问元素
>>> X=np.array([[51,55],[14,19],[0,4]])
>>> print(X)
[[51 55]
[14 19]
[ 0 4]]
>>> X[0]
array([51, 55])
>>> X[0][1]
55
>>> for row in X:
... print(row)
...
[51 55]
[14 19]
[0 4]
>>> X=X.flatten()
>>> print(X)
[51 55 14 19 0 4]
>>> X[np.array([0,2,4])]
array([51, 14, 0])
>>> X>15
array([ True, True, False, True, False, False])
>>> X[X>15]
array([51, 55, 19])
对 NumPy 数组使用不等号运算符等(上例中是 X > 15 ),结果会得到一个布尔型的数组。上例中就是使用这个布尔型数组取出了数组的各个元素(取出 True 对应的元素)
1.6 Matplotlib
1.6.1 绘制简单图形
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,6,0.1)
y=np.sin(x)
plt.plot(x,y)
plt.show()
1.6.2 pyplot 的功能
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(0,6,0.1)
y1=np.sin(x)
y2=np.cos(x)
plt.plot(x,y1,label="sin")
plt.plot(x,y2,linestyle="--",label="cos")
plt.xlabel("x")
plt.ylabel("y")
plt.title('sin&cos')
plt.legend()
plt.show()
1.6.3 显示图像
import matplotlib.pyplot as plt
from matplotlib.image import imread
img = imread('OXA.png')
plt.imshow(img)
plt.show()