花园
1781 字
9 分钟
多模态&机器学习相关笔记
关于大数据技术的核心逻辑框图:
大数据专业核心的思路再与数据的:
- 获取:——购买(或者抓取)————————云端存储(或者本地存储)——————————EDA(探索性数据分析)——————AL(机器学习)
多模态/结构化/非结构化/Transformer/ TP/NP/TN/FN模型选择案例
- 多模态: 多模态本质是让机器也能够同时用好几种”感官“来理解信息。
- 结构化数据:有固定的格式,直接算/查。 其占比20%(eg:姓名,年龄)
- 非结构化数据:像一堆杂乱的文件,无固定的格式,需要理解后使用(eg:图片,视频)
那么我们让AI也能够识别图片模态呢?
图片 ——> 一堆数字(R=255,G=128,B=0,等几百万个像素点)
将每一个东西压缩成一个数字坐标(向量)——> 移交卷积神经网络进行AL训练
| | P N————————|————————————————
P | TP FN
|
N | FP TN
对于上述部分总结:
- 从左到右:实际
- 从上到下:模型评估
- TP:得判得
- FN:miss(得了判没得,漏掉,漏检)
- FP:误判(没有得判得)
- TN:没得判没得
核心公式:
Accuracy = (TP+TN)/m m=TP+TN+FP+FN #模型的准确率
FPR = FP/(FP+TN) #模型的误判率
Precision = TP / (TP+FP) #模型的精确率
Recall = TP/(TP+FN) #模型的召回率根据Precision和Recall我们可以绘制模型的P-R曲线。将P-R曲线推倒,我们可以得到:R-FPR图像;其都为模型选择评估的核心指标!!
对于数据的抓取:
利用好PYTHON脚本可以更加便捷我们的数据分析和处理,从而提出更加便捷的方案。
#python:import requestsimport osimport cv2import numpy as np
url = "http://localhost:4321/images/ghs.png"
headers = { "Accept":"image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5", "Accept-Encoding":"gzip, deflate, br, zstd", "Accept-Language":"zh-CN,zh;q=0.9,zh-TW;q=0.8,zh-HK;q=0.7,en-US;q=0.6,en;q=0.5", "Cache-Control":"no-cache", "Connection":"keep-alive", "Host":"localhost:4321", "Pragma":"no-cache", "Priority":"u=4, i", "Referer":"http://localhost:4321/about/", "Sec-Fetch-Dest":"image", "Sec-Fetch-Mode":"no-cors", "Sec-Fetch-Site":"same-origin", "User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0",}
response = requests.get(url, headers=headers)ext = response.headers['Content-Type'].split('/')[1]
name = 'test'filename = name + '.' + extimg_bytes = response.content
Download_folder = "./Picture"os.makedirs(Download_folder, exist_ok=True)with open(os.path.join(Download_folder, filename), 'wb') as f: f.write(img_bytes)print(filename, "saved")
class cv2_sh(): def cv2_imshow(self, img): cv2.imshow("test", img) cv2.waitKey(0) cv2.destroyAllWindows()
# 将 bytes 解码为 numpy 数组img_array = np.frombuffer(img_bytes, dtype=np.uint8)img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
mycv2_sh = cv2_sh()if img is None: print("图片未找到")else: mycv2_sh.cv2_imshow(img) rows, cols, channel = img.shape print("图片高度:", str(rows), "图片宽度是:", str(cols), "图片的通道数是:", str(channel))#python:import pandas as pd #引入Pandasimport matplotlib.pyplot as plt #引入matplotlib
df = pd.read_csv("S&P500.csv") #读取CSV
plt.rcParams['font.sans-serif'] = ['SimHei'] #设置中文字体SimHeiplt.rcParams['axes.unicode_minus'] = False #正常显示负号-
#print(df.head(5)) #看前5行#print(df.columns) #看列名#print(df['Close']) #看close列所有数据#print(df['Close'].describe()) #看close的统计结果#df['Close'].plot() #画close的折线图
df2 = df[['Date','Close']].iloc[0:300].copy() #定义df2变量,找到Date,Close两列,取0-300
df2["Date"] = pd.to_datetime(df2["Date"]) #Date转换为时间格式
df2 = df2.set_index("Date") #Date设置为索引
df_1 = df2[["Close"]].copy() #准备好第一列,用copy建立好索引df_1.columns = ["原始数据"] #改列名
df_2 = df2[["Close"]].rolling(window=5).mean() #准备第二列,进行滚动平均df_2.columns = ["5日滚动平均"] #改列名
print("df_1.shape:",df_1.shape) #验证切割的前半部分print("df_2.shape:",df_2.shape) #验证切割的后半部分
df_concat = pd.concat([df_1,df_2],axis = 1) #用pd.concat拼接,axis=0表示上下拼接
print("df_concat.shape:",df_concat.head(10)) #看下前十行,验证pd.concat是否拼接成功
#df_concat.plot(figsize = (16,9)) #画出折线图#df2["Close"].rolling(window=5).mean().plot(label="5日滚动平均") #画出5日的滚动平均线(这里没有用我们之前的进行,而是直接拿Close进行的)#plt.title("趋势图",color="green") #命名同时设置标题颜色#plt.legend() #显示图例#plt.show() #显示图片
fig, (ax1,ax2) = plt.subplots(1,2, figsize=(20,8), gridspec_kw={'width_ratios':[2,1]}) #创建左右两个区域
#在左侧画图df_concat.plot(ax=ax1)ax1.set_title("趋势图", color="green")ax1.legend()
#在右侧显示表格(前20行)ax2.axis('off') #关闭坐标轴ax2.table(cellText=df_concat.head(20).values, colLabels=df_concat.columns, rowLabels=df_concat.head(20).index.strftime('%m-%d'), loc='center', cellLoc='center')
plt.tight_layout()plt.show()#python:import pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression
df = pd.read_csv("S&P500.csv")
#print(df.head(10))#print(df.columns)#print(df['Close'])#print(df['Close'].describe())
df_ = pd.concat((df["Close"], df["Close"].rolling(5).mean().rename("roll_5"), df["Close"].rolling(10).mean().rename("roll_10"), df["Close"].rolling(15).mean().rename("roll_15"), df["Close"].rolling(20).mean().rename("roll_20"), df["Close"].rolling(25).mean().rename("roll_25"), df["Close"].rolling(30).mean().rename("roll_30"), df["Close"].shift(-1).rename("y") ),axis=1)
X = df_.iloc[29:-1,0:-1]Y = df_.iloc[29:-1,-1]X_train,X_test,Y_train,Y_test = train_test_split(X,Y,train_size=0.8,random_state=42)
model = LinearRegression()
model.fit(X_train,Y_train)
y_pred = model.predict(X_test)
#print(y_pred)
"""print("X_train shape:",X_train.shape, "X_test shape:",X_test.shape, "Y_train shape:",Y_train.shape, "Y_test shape:",Y_test.shape,)"""
#print(df_,X,Y)#python:url = "http://localhost:4321/images/ghs.png"
headers = { "Accept":"image/avif,image/webp,image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5", "Accept-Encoding":"gzip, deflate, br, zstd", "Accept-Language":"zh-CN,zh;q=0.9,zh-TW;q=0.8,zh-HK;q=0.7,en-US;q=0.6,en;q=0.5", "Cache-Control":"no-cache", "Connection":"keep-alive", "Host":"localhost:4321", "Pragma":"no-cache", "Priority":"u=4, i", "Referer":"http://localhost:4321/about/", "Sec-Fetch-Dest":"image", "Sec-Fetch-Mode":"no-cors", "Sec-Fetch-Site":"same-origin", "User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:153.0) Gecko/20100101 Firefox/153.0",}
response = requests.get(url, headers=headers)ext = response.headers['Content-Type'].split('/')[1]
name = 'test'filename = name + '.' + extimg_bytes = response.content
Download_folder = "./Picture"os.makedirs(Download_folder, exist_ok=True)with open(os.path.join(Download_folder, filename), 'wb') as f: f.write(img_bytes)print(filename, "saved")
class cv2_sh(): def cv2_imshow(self, img): cv2.imshow("test", img) cv2.waitKey(0) cv2.destroyAllWindows()
# 将 bytes 解码为 numpy 数组img_array = np.frombuffer(img_bytes, dtype=np.uint8)img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
mycv2_sh = cv2_sh()if img is None: print("图片未找到")else: mycv2_sh.cv2_imshow(img) rows, cols, channel = img.shape print("图片高度:", str(rows), "图片宽度是:", str(cols), "图片的通道数是:", str(channel))#python:import json
#with open('疫情.txt','r+',encoding = 'utf-8') as f:等效于:f = open('疫情.txt','r+',encoding = 'utf-8') #打开,r+读+写,utf-8data = f.read() #读存数据到data字典f.close() #关
data_dict = json.loads(data) #把JSON格式的长字符串转化为Python字典
'''数据格式:A=[0,1,2,3,4,5...]此时A为列表。B={"1":"5","2":"4","3":"3","4":"2","5":"1"...}此时B为字典,JSON文档不存在元组,即使我们写:json.loads((1,2,3)),导出JSON的时候会转化为[1,2,3]列表。'''
area_data = data_dict["areaTree"] #取出键名为areaTree的键值对,并存入area_data
count = len(area_data) #统计areaTree长度print(count)
print(type(area_data),type(data_dict),type(data),type(f))
province_data = area_data[0]["children"][3] #取到省份的数据
province_name = area_data[0]["children"][3]["name"] #提取到某一个具体省份
city_data = area_data[0]["children"][3]["children"] #该省份所有的城市数据
city_name = area_data[0]["children"][3]["children"][0]["name"] #锁定一个具体城市
city_totle = area_data[0]["children"][3]["children"][0]["total"] #郑州的total
city_confirm = area_data[0]["children"][3]["children"][0]["total"]["confirm"] #拿到需要的具体数据
"""循环实现所有城市的具体数据抓取"""
city_main = [] #先把要循环的数据建立一个空的列表for city in city_data: #在city_data里面循环city name = city["name"] #取name,来自"name" confirm = city["total"]["confirm"] #取confirm,来自total里面的confirm city_main.append((name,confirm)) #把name,confirm存进city_main
print(city_main)
"""area_data (list,长度为1,里面包含的是整个中国的一个大的字典。所以只有一个元素)"""#python:import pandas as pd #引入Pandasimport matplotlib.pyplot as plt #引入matplotlibfrom sklearn.metrics import mean_squared_errorimport numpy as npfrom sklearn.model_selection import train_test_splitimport matplotlib.pyplot as plt #引入matplotlib#from sklearn.linear_model import LinearRegression
df = pd.read_csv("S&P500.csv") #读取CSV
plt.rcParams['font.sans-serif'] = ['SimHei'] #设置中文字体SimHei
plt.rcParams['axes.unicode_minus'] = False #正常显示负号
#df_2:训练预测模型并预测df_ = pd.concat((df["Close"], df["Close"].rolling(5).mean().rename("roll_5"), df["Close"].rolling(10).mean().rename("roll_10"), df["Close"].rolling(15).mean().rename("roll_15"), df["Close"].rolling(20).mean().rename("roll_20"), df["Close"].rolling(25).mean().rename("roll_25"), df["Close"].rolling(30).mean().rename("roll_30"), df["Close"].shift(-1).rename("y") ),axis=1)
X = df_.iloc[29:-1,1:-1]Y = df_.iloc[29:-1,-1]X_train,X_test,Y_train,Y_test = train_test_split(X,Y,train_size=0.8,random_state=42)
#用LinearRegression的线性模型库'''model = LinearRegression()model.fit(X_train,Y_train)y_pred = model.predict(X_test)'''
#手写线性方程求解模型X_train_b = np.c_[np.ones((len(X_train),1)),X_train]X_test_b = np.c_[np.ones((len(X_test),1)),X_test]theta = np.linalg.inv(X_train_b.T.dot(X_train_b)).dot(X_train_b.T).dot(Y_train)y_pred = X_test_b.dot(theta)
df_2 = pd.DataFrame({"预测值": y_pred}, index=Y_test.index).sort_index()print("df_2.shape:",df_2.shape)
#df_1原始数据df_1 = df.loc[Y_test.index,["Close"]].copy()df_1.columns = ["真实值"]df_1 = df_1.sort_index()
#拼接df_concat = pd.concat([df_1, df_2],axis=1)print("df_concat.shape:",df_concat.shape)
#绘图df_concat.tail(300).plot(figsize=(16,8))plt.title("预测 真实",color="green")plt.legend()plt.show()
#使用numpy计算MSE,RMSEMSE_1 = np.mean((Y_test - y_pred) ** 2)RMSE_1 = np.sqrt (MSE_1)
#使用mean_squared_error计算MSE,RMSEMSE_2 = mean_squared_error(Y_test, y_pred)RMSE_2 = np.sqrt(MSE_2)
print("MSE_1(手写版本):",round(MSE_1,4))print("RMSE_1(手写版本):",round(RMSE_1,4))print("MSE_2(调用sklearn):",round(MSE_2,4))print("RMSE_2(调用sklearn):",round(RMSE_2,4))
print("\n模型参数(theta):")print(f"截距 (b): {theta[0]:.4f}")print(f"权重 (a1~a6): {theta[1],theta[2],theta[3],theta[4],theta[5],theta[6]}")#python:import jsonfrom pyecharts.charts import Mapfrom pyecharts.options import ToolboxOpts, TitleOpts, VisualMapOptsfrom pyecharts.globals import *
with open('疫情.txt','r+', encoding = 'utf-8') as f: data = f.read()
data_dict = json.loads(data)
area_data = data_dict["areaTree"]
count = len(area_data)
city_data = area_data[0]["children"][3]["children"]
city_main = []
for city in city_data: name = city["name"] + "市" confirm = city["total"]["confirm"] city_main.append([name,confirm])print(city_main)map_chart = ( Map() .add("sh",city_main,maptype="河南") .set_global_opts( title_opts=TitleOpts(title="河南省疫情分布"), visualmap_opts=VisualMapOpts(max_=100), toolbox_opts=ToolboxOpts(is_show=True) ) )map_chart.render("河南省疫情.html")print("OK")
更多文章
陕公网安备61020002000144号