人工智能学习笔记

人工智能学习笔记


什么是人工智能?

:star:人制造出来的机器,来模仿人的行为。还有就是能够自主学习及解决问题更新自己的知识库。让机器能够像人一样思考和行动。比如以下几种:

  • 人脸识别、车牌识别、自动驾驶
  • 机器翻译、人机互动、GPT
  • 智能机器人、AlphaGO等等

人工智能实现方法:

  • 符号学习:原理是基于逻辑与规则的学习方法,其原理主要为物理符号系统假设和有限合理性原理,不能升级模型。

  • :star:机器学习:从数据中寻找规律、建立关系,根据建立的关系去解决问题的方法,从数据中学习并且实现自我优化升级,其原理是数据驱动。

    :bulb:机器学习是一种实现人工智能的方法,从数据中学习然后对真实世界的时间做出决策和预测,比如,垃圾邮件检测、房价预测等等。

    :bulb:深度学习是一种实现机器学习的技术。模仿人类神经网络,建立模型,进行数据分析,比如,人脸识别、无人驾驶等等。

工具安装:

  • python 官网下载安装
  • jupyter notebook
  • pandas、matplib、numpy

在系统的一个位置新建一个文件夹,比如:e:_log

1
2
3
4
5
6
7
8
9
# 创建虚拟环境
E:\learning_log> python -m venv ai_env

# 激活虚拟环境 关闭虚拟环境用 deactivate
E:\learning_log> ai_env\Scripts\activate

# 安装jupyter notebook
(ll_env) E:\learning_log> python.exe -m pip install --upgrade pip
(ll_env) E:\learning_log> pip install notebook

在虚拟环境的目录下创建一个txt文件并该后缀为bat,编辑内容为:

1
2
3
4
5
6
7
8
9
10
11
12
@echo off
call E:\learning_log> ai_env\Scripts\activate
jupyter notebook --browser=edge
# 这个bat文件是放在和虚拟环境文件夹同个目录,需要复制网址打开编辑器

# 如果需要直接启动的话需要在虚拟环境(激活)下输入jupyter notebook --generate-config
# 这时C盘用户文件夹就会出现一个 C:\Users\用户名\.jupyter 的文件夹
# 打开里面的 jupyter_notebook_config.py 添加一行 c.NotebookApp.use_redirect_file = False
(ll_env) E:\learning_log>jupyter notebook

# 删除虚拟环境
直接删除文件目录就可以了,确保没有激活虚拟环境!

这就启动了jupyter了

安装pandas等

1
2
3
4
# 国内镜像安装
pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple some-package
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple some-package

工具使用和介绍

1
2
x = [1,2,3,4,5]
y = [2,3,4,5,6]

安装和使用matplotlib

1
import matplotlib
1
2
3
4
5
6
7
8
9
10
from matplotlib import pyplot as plt
# 让图形展示的%代码
%matplotlib inline
fig1 = plt.figure(figsize=(5,5))
plt.plot(x,y)
plt.title('y vs x')
plt.xlabel('x')
plt.ylabel('y')

plt.show()
1
2
3
4
5
6
7
8
9
# 散点图plt.scatter(x,y)
fig2 = plt.figure(figsize=(5,5))
plt.scatter(x,y)
plt.title('y vs x')
plt.xlabel('x')
plt.ylabel('y')

plt.show()

安装和使用numpy

1
2
3
4
import numpy as np
a = np.eye(5)
print(type(a))
print(a)
<class 'numpy.ndarray'>
[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]]
1
2
3
4
b = np.ones([5,5])
print(b)
# 显示行列
print(b.shape)
[[1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1.]]
(5, 5)
1
2
3
c = a + b
print(c.shape)
print(c)
(5, 5)
[[2. 1. 1. 1. 1.]
 [1. 2. 1. 1. 1.]
 [1. 1. 2. 1. 1.]
 [1. 1. 1. 2. 1.]
 [1. 1. 1. 1. 2.]]

安装和使用pandas

这里有个提示:就是有时候windows的路径是反斜杠,我们需要改成正斜杠。

1
2
3
import pandas as pd
data = pd.read_csv('./data.csv')
print(data)
      Name  Age         City
0    Alice   24     New York
1      Bob   27  Los Angeles
2  Charlie   22      Chicago
3    David   32      Houston
4      Eve   29      Phoenix
1
2
name = data.loc[:,'Name']
print(name)
0      Alice
1        Bob
2    Charlie
3      David
4        Eve
Name: Name, dtype: object
1
2
age = data.loc[:,'Age']
print(age)
0    24
1    27
2    22
3    32
4    29
Name: Age, dtype: int64
1
2
3
# 筛选
c = data.loc[:,'Age'][age>25]
print(c)
1    27
3    32
4    29
Name: Age, dtype: int64
1
2
3
# pandas转换为numpy
data_array = np.array(data)
print(data_array)
[['Alice' 24 'New York']
 ['Bob' 27 'Los Angeles']
 ['Charlie' 22 'Chicago']
 ['David' 32 'Houston']
 ['Eve' 29 'Phoenix']]

保存为本地文件

1
2
3
4
data_new = age + 1
data_new.head()
# 保存,如果要去除索引列 to_csv( '1.csv',index=None)
data_new.to_csv('data_new.csv',index=None)

机器学习——线性回归

机器学习是一种实现人工智能的方法,从数据中寻找规律、建立关系,根据建立的关系去解决问题。

机器学习应用场景:

  • 数据挖掘
  • 计算机视觉
  • 自然语言处理
  • 证券分析
  • 医学诊断
  • 机器人
  • DNA测序等等

机器学习基本框架:数据——>函数——>解决问题

机器学习类别:

  • 监督学习

    告诉机器什么是对的

    • 线性回归
    • 逻辑回归
    • 决策树
    • 神经网络、卷积神经网络、循环神经网络
  • 无监督学习

    让机器自己去数据中寻找规律

    • 聚类算法
  • 半监督学习

    告诉机器一部分正确的,剩下的让机器自己去理解

  • 强化学习(深度学习)

    根据每次结果收获的奖惩进行学习,实现优化

线性回归

找到两个(或两个以上)数据对应关系的一条线,通过拟合这条线进行新的预测。

\(y = ax + b\)其中a为斜率,b为截距(y为0或者x为0的时候另一个点在哪里)

\(y = f(x_1,x_2\dots x_n)\)

  • 一元回归:\(y=f(x)\)
  • 多元回归:\(y = f(x_1,x_2\dots x_n)\)
  • 线性回归:\(y=ax+b\)
  • 非线性回归:\(y=ax^2+bx+c\)

\(j = \frac{1}{2m}\sum_{i=1}^{m}(y_1-y)^2 = \frac{1}{2m}\sum_{i=1}^{m}(ax_i+b-y_i)^2 = g(a,b)\) j的值越小,就代表越接近真实的值。

线性回归实战准备

1
2
3
4
5
6
7
8

任务:基于generated_data.csv数据,建立线性回归模型,预测x=3.5对应的y值,评估模型表现(lr.model.coef_和lr_model.intercept_)


```python
# 加载数据
import pandas as pd
data = pd.read_csv('./data/generated_data.csv')
1
data.head()
x y
0 1 7
1 2 9
2 3 11
3 4 13
4 5 15
1
2
3
# 数据赋值
x = data.loc[:,'x']
y = data.loc[:,'y']
1
2
3
4
5
# 展示图形
from matplotlib import pyplot as plt
plt.figure(figsize=(5,5))
plt.scatter(x,y)
plt.show()

python调用Sklearn实现线性回归

1
2
3
4
5
6
7
8
9
10
11
12
# 建立线性回归模型
from sklearn.linear_model import LinearRegression
import numpy as np
lr_model = LinearRegression()

# 用numpy将一维数据转换为二维数据
x = np.array(x)
x = x.reshape(-1,1)
y = np.array(y)
y = y.reshape(-1,1)

lr_model.fit(x,y)
1
2
3
4
5
6
7
# 预测模型
y_predict = lr_model.predict(x)
# print(y_predict)

# 这里需要注意,如果直接给数值预测会报错,我们需要把数值转换成二维的,就是[[3.5]]这个样子
y_predict_2 = lr_model.predict([[3.5]])
print(y_predict_2)
[[12.]]
1
2
3
4
# 打印a、b就是y = ax + b中的,a是斜率,b是截距
a = lr_model.coef_
b = lr_model.intercept_
print(a,b)
[[2.]] [5.]
1
2
3
4
5
6
7
8
9
# 评估模型----MSE越接近0越好,r2越接近1越好
from sklearn.metrics import mean_squared_error,r2_score
MSE = mean_squared_error(y,y_predict)
R2 = r2_score(y,y_predict)
print(MSE,R2)

plt.figure()
plt.plot(y,y_predict)
plt.show()
3.1554436208840474e-31 1.0

Ashare用法

from Ashare import *

df=get_price('sh000001',frequency='1d',count=5) #默认获取今天往前5天的日线实时行情 print('上证指数日线行情',df)

df=get_price('000001.XSHG',frequency='1d',count=5,end_date='2021-04-30') #可以指定结束日期,获取历史行情 print('上证指数历史行情',df)

df=get_price('000001.XSHG',frequency='1w',count=5,end_date='2018-06-15') #支持'1d'日, '1w'周, '1M'月
print('上证指数历史周线',df)

df=get_price('sh600519',frequency='15m',count=5) #分钟线实时行情,可用'1m','5m','15m','30m','60m' print('贵州茅台15分钟线',df)

df=get_price('600519.XSHG',frequency='60m',count=6) #分钟线实时行情,可用'1m','5m','15m','30m','60m' print('贵州茅台60分钟线',df)

完整代码:多家公司股价预测

1. 安装依赖包

确保你已经安装了必要的库:

1
pip install pandas numpy scikit-learn matplotlib

2. 准备 CSV 文件

假设你的 CSV 文件结构如下(文件名为 stock_data.csv):

Date Open High Low Close Volume
2024-01-01 150.00 155.00 148.00 152.00 1000000
2024-01-02 210.00 215.00 208.00 212.00 1500000
... ... ... ... ... ...

3. 机器学习代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import numpy as np

# 加载数据
data = pd.read_csv('stock_data.csv')

# 查看数据
print(data.head())

# 数据预处理
data['Date'] = pd.to_datetime(data['Date'])
data.set_index('Date', inplace=True)

# 为每个公司添加前一天的收盘价和开盘价作为特征
data['Prev_Close'] = data['Close'].shift(1)
data['Prev_Open'] = data['Open'].shift(1)
data.dropna(inplace=True) # 删除缺失值

# 特征和标签
features = data[['Prev_Close', 'Prev_Open']]
target = data['Close']

# 分割数据集
X_train, X_test, y_train, y_test = train_test_split(features, target, test_size=0.2, random_state=42)

# 构建模型
model = LinearRegression()
model.fit(X_train, y_train)

# 预测
predictions = model.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, predictions)
print(f"Mean Squared Error: {mse}")

# 查看预测值和实际值
result = pd.DataFrame({'Actual': y_test, 'Predicted': predictions})
print(result.head())

# 绘制预测值和实际值对比图
plt.figure(figsize=(12, 6))
plt.plot(result.index, result['Actual'], label='Actual', color='blue', marker='o')
plt.plot(result.index, result['Predicted'], label='Predicted', color='red', linestyle='--', marker='x')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.title('Stock Price Prediction')
plt.legend()
plt.show()

4. 使用方法说明

  1. 加载数据:
    • 将你的 CSV 文件(如 stock_data.csv)存放在脚本的同一目录中,或使用绝对路径。
    • 使用 pandas.read_csv() 函数加载 CSV 数据。
  2. 数据预处理:
    • 将日期列转换为 datetime 类型并设为索引。
    • 为所有记录添加前一天的开盘价和收盘价作为特征,并删除缺失值。
  3. 数据分割:
    • 使用 train_test_split() 将数据集分为训练集和测试集。test_size=0.2 表示 20% 的数据用于测试。
  4. 模型训练:
    • 使用 LinearRegression 构建线性回归模型。
    • 调用 fit() 方法训练模型。
  5. 预测与评估:
    • 使用 predict() 方法对测试集进行预测。
    • 计算均方误差(MSE)评估模型性能。
  6. 结果展示:
    • 将预测值和实际值显示出来,以比较模型的预测效果。
  7. 图形化展示:
    • 使用 matplotlib 库绘制预测值与实际值的对比图,帮助你直观地了解模型的表现。

注意事项

  • 你可以将 CSV 文件替换为你自己的股票数据,确保文件的格式与示例相匹配。
  • 该示例使用简单的线性回归模型,可以尝试其他高级模型(如 LSTM、XGBoost)以提高预测效果。
  • 数据中的噪声和不可预测性可能会影响预测准确性,在实际应用中需要小心处理。

人工智能学习笔记
http://example.com/2024/10/04/2024-10-04-机器学习/
作者
zqten
发布于
2024年10月4日
许可协议