机器视觉学习总结
时间:2023-02-23 10:00:00
本文是对前段时间机器学习内容的总结和回顾,可以为继续学习的人提供指导;非常感谢协会的组织、老师的解释和一起努力学习的朋友。努力工作,努力工作总是有收获的。在阅读过程中,如果您有任何问题,或改进建议,或写错地方,请指出,方便您更好地阅读。谢谢你的支持!
1 环境配置
1.1 Python
python的安装包:python 3.8
1.2 配置anaconda
参考地址:https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/
1.3 安装pycharm
1.4 绘制plot figure
import matplotlib.pyplot as plt import numpy as np x = np.linspace(0.05,20,2000) y = np.sin(x) plt.plot(x,y,ls='--',c='k',lw=2,label='plot figure') plt.legend() plt.axhline(0.5,ls='-.',c='r',lw=1) plt.axvline(7.5,ls='-.',c='r',lw=1) plt.savefig('E:\\test\\test.png',dpi=300) plt.show()
结果:
2 数据分析
2.1 预测房价
第一种方法:
def cal_price(city, area): if area<0: print(面积输入错误,请重新输入!) return 0 if city == "深圳": if area < 100: return area * 70000 else: return area * 60000 elif city == "广州": if area < 90: return area * 40000 else: return area * 30000 else: return area * 60000 print("请输入城市名称:")
city = input()
print("请输入房屋面积:")
area = int(input())
house_price = cal_price(city, area)
if house_price==0:
print('输入错误,请重新输入!')
else:
print("房屋的价格:%d" % house_price)
结果:
C:\ProgramData\Anaconda3\python.exe D:/test/test.py
请输入城市名称:
深圳
请输入房屋面积:
300
房屋的价格:18000000
进程已结束,退出代码为 0
第二种方式:
def cal_price(city,squar):
if squar <0:
print('面积输入错误,请重新输入!')
return 0
if city == "深圳":
if squar < 100:
HP = squar * 7
else:
HP = squar * 6
elif city =="广州":
if squar < 90:
HP = squar * 4
else:
HP = squar * 3
else:
HP =squar * 6
return HP
def main():
city = input("请输入你的城市:")
squar = int(input("请输入房子的面积:"))
price= cal_price(city,squar)
print("您的房价是:" + str(price))
if __name__ == '__main__':
main()
第三种方式:
def GetHousePrice(city,area):
if city =='深圳':
if area < 100:
HP = 7 * area
else:
HP = 6 * area
elif city == '广州':
if area < 90:
HP = 4 * area
else:
HP = 3 * area
else:
HP = 6 * area
return HP
def main():
city = input("请输入你的城市:")
area = int(input("请输入房子的面积:"))
HP = GetHousePrice(city,area)
print("您的房价是:"+str(HP))
if __name__ == '__main__':
main()
2.2 预测波士顿房价
from sklearn.linear_model import LinearRegression #导入线性回归 from sklearn.datasets import load_boston #导入波士顿的数据集 from sklearn.model_selection import train_test_split #模型划分,训练集,测试集 boston = load_boston() print(boston) x = boston['data'] #取出boston字典里的data数据 y = boston['target'] #取出boston字典里边的target数据 #1、划分训练集和测试集 特征数据x
标签数据y 训练集 x_train y_train 测试集 x_test y_test from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3) #2和3 model_test =LinearRegression().fit(x_train,y_train) #4、预测 y_pred = model_test.predict(x_test) print(y_pred) #图形展示 import matplotlib.pyplot as plt plt.plot(range(y_test.shape[0]),y_test,color='blue',linewidth=1.5,linestyle='-') plt.plot(range(y_test.shape[0]),y_pred,color='red',linewidth=1.5,linestyle='-.') plt.legend(['y_test','y_pred']) plt.show()
结果:
2.3 鸢尾花的算法
第一种方式:
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import pandas as pd
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
TRAIN_URL = r'http://download.tensorflow.org/data/iris_training.csv'
train_path = tf.keras.utils.get_file(TRAIN_URL.split('/')[-1], TRAIN_URL)
names = ['Sepal length', 'Sepal width', 'Petal length', 'Petal width', 'Species']
df_iris = pd.read_csv(train_path, header=0, names=names)
iris_data = df_iris.values
plt.figure(figsize=(15, 15), dpi=60)
for i in range(4):
for j in range(4):
plt.subplot(4, 4, i * 4 + j + 1)
if i == 0:
plt.title(names[j])
if j == 0:
plt.ylabel(names[i])
if i == j:
plt.text(0.3, 0.4, names[i], fontsize=15)
continue
plt.scatter(iris_data[:, j], iris_data[:, i], c=iris_data[:, -1], cmap='brg')
plt.tight_layout(rect=[0, 0, 1, 0.9])
plt.suptitle('鸢尾花数据集\nBule->Setosa | Red->Versicolor | Green->Virginica', fontsize=20)
plt.show()
结果:
第二种方式:
from sklearn import datasets
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
iris = datasets.load_iris()
# 2.取特征空间中的4个维度
X = iris.data[:, :4]
# 3.搭建模型,构造KMeans聚类器,聚类个数为3
estimator = KMeans(n_clusters=3)
#开始聚类训练
estimator.fit(X)
# 获取聚类标签
label_pred = estimator.labels_
# 绘制数据分布图(数据可视化)
plt.scatter(X[:, 0], X[:, 1], c="red", marker='o', label='see')
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
plt.show()
# 绘制k-means结果
x0 = X[label_pred == 0]
x1 = X[label_pred == 1]
x2 = X[label_pred == 2]
plt.scatter(x0[:, 0], x0[:, 1], c="red", marker='o', label='label0')
plt.scatter(x1[:, 0], x1[:, 1], c="green", marker='*', label='label1')
plt.scatter(x2[:, 0], x2[:, 1], c="blue", marker='+', label='label2')
#花瓣的长宽
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc=2)
plt.show()
结果:
第三种方式:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
# 载入数据集
iris_dataset = load_iris()
# 数据划分
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)
# 设置邻居数
knn = KNeighborsClassifier(n_neighbors=1)
# 构建基于训练集的模型
knn.fit(X_train, y_train)
# 一条测试数据
X_new = np.array([[5, 2.9, 1, 0.2]])
# 对X_new预测结果
prediction = knn.predict(X_new)
print("预测值%d" % prediction)
# 得出测试集X_test测试集的分数
print("score:{:.2f}".format(knn.score(X_test, y_test)))
结果:
2.4 根据Excel中每列进行展示
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] =["SimHei"] #设置字体
plt.rcParams["axes.unicode_minus"] =False #该语句解决图像种的“-”负号的乱码问题
#读取原始文件内容
ori_data = pd.read_excel(r"E:\test\客户数据-all-1.xlsx")
#初步筛选出已经购买课程的群体
df = pd.DataFrame(ori_data[ori_data["是否购买课程"]==1])
#先获取表格中的列名
columns_name = np.array(df.columns)
#输入列名
print(columns_name)
def statistics_classification(name):
#筛选出需要的数据并且回执条形图形
df[name].value_counts().plot(kind="bar")
#图形标题
plt.title("按照"+name+"分类统计")
#X坐标轴显示旋转
plt.xticks(rotation=60)
plt.show()
name = input("请输入想要筛选的内容:")
if name not in columns_name:
print("输入的内容错误")
else:
statistics_classification(name)
结果:
C:\ProgramData\Anaconda3\python.exe D:/test/test.py
['Unnamed: 0' 'Unnamed: 0.1' 'Unnamed: 0.1.1' '手机号' '性别' '年龄' '学历水平'
'婚姻状态' '常居城市' '子女年龄' '是否购买过少儿课程' '是否体验过本课程' '是否购买过少儿保险' '客户财富等级'
'是否去过高端商场' '是否去过高尔夫球场' '是否住在高端小区' '是否喜欢旅游' '是否出过国' '客户是否有房' '房价' '是否有车'
'销售渠道' '行业分类' '英语水平' '健康状况' '是否购买课程']
请输入想要筛选的内容:学历水平
3 神经网络
3.1 图片处理工具
https://colorize.cc/
https://cloud.baidu.com/product/imageprocess/colourize?track=cp:nsem%7Cpf:PC%7Cpp:P-fengchao124-tuxiangzengqiangtexiao-bayue%7Cpu:heibaitupianshangse%7Cci:%7Ckw:10368400&bd_vid=9996180438037139433
3.2 安装tensorflow
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple tensorflow==2.6.0
3.3 预测房价
dict = {
'深圳':80,'广州':90}
print(dict)
city=input("请输入城市:")
# area=input("请输入面积:")
for d in dict:
if d == city and city == '深圳':
print(d)
price = dict[d] * 7
break;
elif d == city and city == '广州':
print(d)
price = dict[d] * 6
break;
print(price)
结果:
C:\ProgramData\Anaconda3\python.exe D:/test/test.py
{
'深圳': 80, '广州': 90}
请输入城市:广州
广州
540
3.4 生成矩阵
![# import tensorflow as tf
# tf.__version__
# print(tf.__version__)
# # 常量
# a =tf.constant(3)
# b =tf.constant(2)
#
# #生成一个1*3的数组
# c =tf.Variable(tf.constant([1,2,3]))
# print(c)在这里插入图片描述
#
# #生成矩阵
# c0= tf.zeros([10,33])
# c1= tf.ones([10,33])
# c2= tf.fill([10,33],2.)
#
# #矩阵的运算
# print('c2+c1',tf.add(c2,c1))
# print('c2-c1',tf.subtract(c1,c2))
# #乘法
# print('c2+c1',tf.multiply(c2,c1))
# #除法
# print('c2+c1',tf.divide(c2,c1))
# print(c1)]
结果:
C:\ProgramData\Anaconda3\python.exe D:/test/test.py 2022-07-12 16:19:55.812000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2022-07-12 16:19:55.869000: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 2.6.0 2022-07-12 16:20:56.844000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2022-07-12 16:20:56.846000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cublas64_11.dll'; dlerror: cublas64_11.dll not found 2022-07-12 16:20:56.849000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cublasLt64_11.dll'; dlerror: cublasLt64_11.dll not found 2022-07-12 16:20:56.851000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cufft64_10.dll'; dlerror: cufft64_10.dll not found 2022-07-12 16:20:56.855000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'curand64_10.dll'; dlerror: curand64_10.dll not found 2022-07-12 16:20:56.857000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cusolver64_11.dll'; dlerror: cusolver64_11.dll not found 2022-07-12 16:20:56.860000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cusparse64_11.dll'; dlerror: cusparse64_11.dll not found 2022-07-12 16:20:56.863000: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'cudnn64_8.dll'; dlerror: cudnn64_8.dll not found 2022-07-12 16:20:56.863000: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1835] Cannot dlopen some GPU libraries. Please make sure the missing libraries mentioned above are installed properly if you would like to use GPU. Follow the guide at https://www.tensorflow.org/install/gpu for how to download and setup the required libraries for your platform. Skipping registering GPU devices... 2022-07-12 16:20:56.938000: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. <tf.Variable 'Variable:0' shape=(3,) dtype=int32, numpy=array([1, 2, 3])> c2+c1 tf.Tensor( [[3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.] [3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3. 3.]], shape=(10, 33), dtype=float32) c2-c1 tf.Tensor( [[-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. -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. -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. -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. -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. -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. -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. -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. -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. -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. -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. -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. -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. -1. -1. -1. -1. -1.]], shape=(10, 33), dtype=float32) c2+c1 tf.Tensor( [[2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 元器件数据手册
、IC替代型号,打造电子元器件IC百科大全!