diff --git a/03_pycharm_python_coursework_20240427/DecisionTree.py b/03_pycharm_python_coursework_20240427/DecisionTree.py new file mode 100644 index 0000000..fee46f3 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/DecisionTree.py @@ -0,0 +1,23 @@ +from sklearn import tree + +# 特征数据 身高 体重 +# 1 - 有 +# 0 - 无 +features = [[178, 1], [155, 0], [180, 1]] +# 特征值 +labels = ['male', 'female', 'male'] + +def decision_tree_classifier(): + # 创建分类器 + clf = tree.DecisionTreeClassifier() + # 模型训练 + clf = clf.fit(features, labels) + # 预测 + r1 = clf.predict([[158, 0]]) + print('Data[158, 0] is label for: ', r1) + + r2 = clf.predict([[190, 1]]) + print('Data[190, 1] is label for: ', r2) + +if __name__ == '__main__': + decision_tree_classifier() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/DeepLearn.py b/03_pycharm_python_coursework_20240427/DeepLearn.py new file mode 100644 index 0000000..571f5b0 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/DeepLearn.py @@ -0,0 +1,19 @@ +import networkx as nx +import matplotlib.pyplot as plt + +G = nx.DiGraph() + +G.add_node("输入层") +G.add_node("隐藏层 1") +G.add_node("隐藏层 2") +G.add_node("输出层") + +G.add_edge("输入层", "隐藏层 1") +G.add_edge("输入层", "隐藏层 2") +G.add_edge("隐藏层 1", "输出层") +G.add_edge("隐藏层 2", "输出层") + +pos = nx.spring_layout(G) +nx.draw_networkx(G, pos) +plt.rcParams['font.sans-serif']=['SimHei'] +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/Kmeans.py b/03_pycharm_python_coursework_20240427/Kmeans.py new file mode 100644 index 0000000..c1dedd0 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/Kmeans.py @@ -0,0 +1,24 @@ +import numpy as np +import matplotlib.pyplot as plt +from sklearn.cluster import KMeans +from sklearn.preprocessing import StandardScaler + +from sklearn.datasets import make_blobs +from sklearn import metrics + +n_samples = 1500 +x, y = make_blobs(n_samples=n_samples, centers=4, random_state=170) + +x = StandardScaler().fit_transform(x) + +KMeans = KMeans(n_clusters=4, n_init='auto', random_state=170) +KMeans.fit(x) + +plt.figure(figsize=(12, 6)) +plt.subplot(121) +plt.scatter(x[:, 0], x[:, 1], c='r') +plt.title("Before clustering") +plt.subplot(122) +plt.scatter(x[:, 0], x[:, 1], c=KMeans.labels_) +plt.title("After clustering") +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/LinearRegression.py b/03_pycharm_python_coursework_20240427/LinearRegression.py new file mode 100644 index 0000000..bba8f2f --- /dev/null +++ b/03_pycharm_python_coursework_20240427/LinearRegression.py @@ -0,0 +1,26 @@ +import numpy as np +import matplotlib.pyplot as plt + +# 转化矩阵 +x = np.linspace(0, 10, 30).reshape(-1, 1) + +# 斜率和截距 随机生成 +w = np.random.randint(1, 5, 1) +b = np.random.randint(1, 10, 1) + +# 根据一元一次方程计算目标值 y , 并加上 噪声, 数据上下有波动 +y = x * w + b + np.random.randn(30, 1) +plt.scatter(x, y) + +# 重构 x, b 截距 +x = np.column_stack([x, np.full((30, 1), 1)]) + +# 正规方程求解 +a = np.linalg.inv(x.T.dot(x)).dot(x.T).dot(y).round(2) + +print(w, b) +print(a) + +# 输出回归线性图 +plt.plot(x[:, 0], x.dot(a), 'green') +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/NaiveBayesAlgorithm.py b/03_pycharm_python_coursework_20240427/NaiveBayesAlgorithm.py new file mode 100644 index 0000000..26cb8cd --- /dev/null +++ b/03_pycharm_python_coursework_20240427/NaiveBayesAlgorithm.py @@ -0,0 +1,21 @@ +import numpy as np +from sklearn.naive_bayes import BernoulliNB + +x = np.array([[0, 1, 0, 1], [1, 1, 1, 1], [1, 1, 1, 0], + [0, 1, 1, 0], [0, 1, 0, 0], [0, 1, 0, 1], + [1, 1, 0, 1], [1, 0, 0, 1], [1, 1, 0, 1], + [0, 0, 0, 0]]) + +# 有风-潮湿-多云-闷热 +y = np.array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0]) +bnb = BernoulliNB() +bnb.fit(x, y) +day_pre = [[1, 0, 1, 0]] +pre = bnb.predict(day_pre) +print("预测结果如下:\n", "*" * 50) +print("结果为: ", pre) +print("*" * 50) + +# 进一步查看概率分析 +pre_pro = bnb.predict_proba(day_pre) +print("不下雨的概率为: ", pre_pro[0][0], "\n下雨的概率为: ", pre_pro[0][1]) diff --git a/03_pycharm_python_coursework_20240427/RandomForest.py b/03_pycharm_python_coursework_20240427/RandomForest.py new file mode 100644 index 0000000..ff8392b --- /dev/null +++ b/03_pycharm_python_coursework_20240427/RandomForest.py @@ -0,0 +1,45 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.colors import ListedColormap +from sklearn.model_selection import train_test_split +from sklearn.ensemble import RandomForestClassifier +from sklearn import datasets + +# 载入红酒数据 +wine = datasets.load_wine() + +# 只选取前两个特征 +x = wine.data[:, :2] +y = wine.target + +# 拆分训练集和数据集 +x_train, x_test, y_train, y_test = train_test_split(x, y) + +forest = RandomForestClassifier(n_estimators=6, random_state=3) + +# 拟合数据 +forest.fit(x_train, y_train) + +# 绘制图形 +cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF']) +cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF']) + +x_min, x_max = x[:, 0].min() - 1, x[:, 0].max() + 1 +y_min, y_max = x[:, 1].min() - 1, x[:, 1].max() + 1 + +xx, yy = np.meshgrid(np.arange(x_min, x_max, .02), np.arange(y_min, y_max, .02)) + +# 生成随机森林 +z = forest.predict(np.c_[xx.ravel(), yy.ravel()]).reshape(xx.shape) + +plt.figure() +plt.pcolormesh(xx, yy, z, cmap=cmap_light) + +# 绘制训练数据和测试数据的散点图 +plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=cmap_bold, edgecolor='k', s=20) +plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=cmap_bold, edgecolor='k', s=50, marker='x') + +plt.xlim(xx.min(), xx.max()) +plt.ylim(yy.min(), yy.max()) +plt.title("Random Forest Classification") +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/main.py b/03_pycharm_python_coursework_20240427/main.py new file mode 100644 index 0000000..5596b44 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/main.py @@ -0,0 +1,16 @@ +# This is a sample Python script. + +# Press Shift+F10 to execute it or replace it with your code. +# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. + + +def print_hi(name): + # Use a breakpoint in the code line below to debug your script. + print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. + + +# Press the green button in the gutter to run the script. +if __name__ == '__main__': + print_hi('PyCharm') + +# See PyCharm help at https://www.jetbrains.com/help/pycharm/ diff --git a/03_pycharm_python_coursework_20240427/opencv_01.py b/03_pycharm_python_coursework_20240427/opencv_01.py new file mode 100644 index 0000000..c547df7 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/opencv_01.py @@ -0,0 +1,13 @@ +import numpy as np +import cv2 +import matplotlib.pyplot as plt +# 读取图片 +img = cv2.imread('source/data_01.png') +orb = cv2.ORB_create() + +keypoints, descriptors = orb.detectAndCompute(img, None) + +output_image = cv2.drawKeypoints(img, keypoints, None, color=(0, 255, 0), flags=0) +cv2.imshow('Feature KeyPoints', output_image) +cv2.waitKey(0) +cv2.destroyWindow() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/opencv_02.py b/03_pycharm_python_coursework_20240427/opencv_02.py new file mode 100644 index 0000000..aad9656 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/opencv_02.py @@ -0,0 +1,68 @@ +import cv2 +import matplotlib.pyplot as plt +import numpy as np + +img = cv2.imread('source/data_02.jpg') + +plt.subplot(3, 3, 1) +plt.imshow(img) +plt.axis('off') +plt.title('BGR') + +# BGR -> RGB +img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) +plt.subplot(3, 3, 2) +plt.imshow(img_RGB) +plt.axis('off') +plt.title('RGB') + +# 原图 -> 灰度 +img_GRAY = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) +plt.subplot(3, 3, 3) +plt.imshow(img_GRAY) +plt.axis('off') +plt.title('GRAY') + +# HSV +img_HSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) +plt.subplot(3, 3, 4) +plt.imshow(img_HSV) +plt.axis('off') +plt.title('HSV') + +# TCrCb +img_YcrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb) +plt.subplot(3, 3, 5) +plt.imshow(img_YcrCb) +plt.axis('off') +plt.title('YcrCb') + +# HLS +img_HLS = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) +plt.subplot(3, 3, 6) +plt.imshow(img_HLS) +plt.axis('off') +plt.title('HLS') + +# XYZ +img_XYZ = cv2.cvtColor(img, cv2.COLOR_BGR2XYZ) +plt.subplot(3, 3, 7) +plt.imshow(img_XYZ) +plt.axis('off') +plt.title('XYZ') + +# LAB +img_LAB = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) +plt.subplot(3, 3, 8) +plt.imshow(img_LAB) +plt.axis('off') +plt.title('LAB') + +# YUV +img_YUV = cv2.cvtColor(img, cv2.COLOR_BGR2YUV) +plt.subplot(3, 3, 9) +plt.imshow(img_YUV) +plt.axis('off') +plt.title('LAB') + +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/opencv_03.py b/03_pycharm_python_coursework_20240427/opencv_03.py new file mode 100644 index 0000000..5c889a6 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/opencv_03.py @@ -0,0 +1,22 @@ +import cv2 +import numpy as np +from PIL import Image +import matplotlib.pyplot as plt + +img_1 = cv2.imread('source/data_03.jpg') +cv2.imshow("img1", img_1) +img_2 = np.zeros(img_1.shape, dtype=np.uint8) +img_2[200:400, 200:400] = 255 +cv2.imshow("img2", img_2) + +result_or = cv2.bitwise_or(img_1, img_2) +result_and = cv2.bitwise_and(img_1, img_2) +result_not = cv2.bitwise_not(img_1, img_2) +result_xor = cv2.bitwise_xor(img_1, img_2) + +cv2.imshow("or", result_or) +cv2.imshow("and", result_and) +cv2.imshow("not", result_not) +cv2.imshow("xor", result_xor) +cv2.waitKey() +cv2.destroyWindow() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/opencv_04.py b/03_pycharm_python_coursework_20240427/opencv_04.py new file mode 100644 index 0000000..90acd8b --- /dev/null +++ b/03_pycharm_python_coursework_20240427/opencv_04.py @@ -0,0 +1,17 @@ +import cv2 + +img = cv2.imread("source/data_02.jpg") + +faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') + +gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + +faces = faceCascade.detectMultiScale(gray, scaleFactor=1.09, minNeighbors=3, minSize=(5, 5)) +print(faces) +print("该图一共有{0}人脸".format(len(faces))) +for(x, y, w, h) in faces: + cv2.circle(img, (int((2 * x + w) / 2), int((2 * y + h) / 2)), + int(w / 2), (0, 255, 0), 2) +cv2.imshow("result", img) +cv2.waitKey() +cv2.destroyWindow() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/pca.py b/03_pycharm_python_coursework_20240427/pca.py new file mode 100644 index 0000000..fe062f3 --- /dev/null +++ b/03_pycharm_python_coursework_20240427/pca.py @@ -0,0 +1,20 @@ +import numpy as np +import matplotlib.pyplot as plt +from sklearn.decomposition import PCA +from sklearn.datasets import load_iris + +# 加载数据 +iris = load_iris() +x = iris.data + +# 执行 PCA +pca = PCA(n_components=2) +x_reduced = pca.fit_transform(x) + +# 绘制结果 +plt.figure(figsize=(10, 5)) +plt.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target) +plt.xlabel('First Principal Component') +plt.ylabel('Second Principal Component') +plt.title('PCA of Iris Dataset') +plt.show() \ No newline at end of file diff --git a/03_pycharm_python_coursework_20240427/source/data_01.png b/03_pycharm_python_coursework_20240427/source/data_01.png new file mode 100644 index 0000000..5bb0167 Binary files /dev/null and b/03_pycharm_python_coursework_20240427/source/data_01.png differ diff --git a/03_pycharm_python_coursework_20240427/source/data_02.jpg b/03_pycharm_python_coursework_20240427/source/data_02.jpg new file mode 100644 index 0000000..530aa95 Binary files /dev/null and b/03_pycharm_python_coursework_20240427/source/data_02.jpg differ diff --git a/03_pycharm_python_coursework_20240427/source/data_03.jpg b/03_pycharm_python_coursework_20240427/source/data_03.jpg new file mode 100644 index 0000000..fc001a3 Binary files /dev/null and b/03_pycharm_python_coursework_20240427/source/data_03.jpg differ