MTM5004 Assignment 4 - Clustering

Pandas入门教程(二十二):股票数据分析实战——yfinance 获取数据、技术指标与收益率分析 把 Pandas 用在真实场景,才能体会它的价值。本文以茅台股票为例,用 yfinance 获取历史行情,完成缺失值处理与列筛选,绘制收盘价曲线,计算 SMA 移动平均线与 RSI 相对强弱指数,并通过日收益率、累计收益率和波动率完成完整的量化分析流程。 阅读详情

MTM5004 Assignment 4 - Clustering (10 Marks)

Hello everyone, this assignment notebook covers Clustering. There are some code-completion tasks and question-answering tasks in this answer sheet. For code completion tasks, please write down your answer (i.e., your lines of code) between sentences that “Your code starts here” and “Your code ends here”. The space between these two lines does not reflect the required or expected lines of code. For answers in plain text, you can refer to this Markdown guide to customize the layout (although it shouldn’t be needed).

When you work on this notebook, you can insert additional code cells (e.g., for testing) or markdown cells (e.g., to keep track of your thoughts). However, before the submission, please remove all those additional cells again. Thanks!

Important:

  • Rename and save this Jupyter notebook as mtm5004_a4_YourName_YourNUSNETID.ipynb (e.g., mtm5004_a4_BobSmith_e12345678.ipynb) before submission!
  • Submission deadline is Thursday, Jan 18, 11.59 pm. Late submissions will be penalized by 10% for each additional day. Failure to appropriately rename both files will yield a penalty of 1 Point. There is no need to use your full name if it’s rather long; it’s just important to easily identify you in Canvas etc.

Please also add your NUSNET and student id in the code cell below. This is just to make any identification of your notebook doubly sure.

student_id = ''
nusnet_id = ''

Here is an overview over the tasks to be solved and the points associated with each task. The notebook can appear very long and verbose, but note that a lot of parts provide additional explanations, documentation, or some discussion. The code and markdown cells you are supposed to complete are well, but you can use the overview below to double-check that you covered everything.

  • 1 K-Means (7 Points)
    • 1.1 Performing K-Means “By Hand” (1 Point)
    • 1.2 Implementing K-Means++ (4 Points)
      • 1.2 a) Initializing Centroids (2 Points)
      • 1.2 b) Assigning Data Points to Clusters (1 Point)
      • 1.2 c) Updating the Centroids (1 Point)
    • 1.2 Questions about K-Means (2 Points)
  • 2 Hierarchical Clustering with AGNES (3 Points)
    • 2.1 Interpreting Dendrograms (2 Points)
    • 2.2 Comparing Linkage Methods (1 Point)

Setting up the Notebook

Importing Required Packages

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import euclidean_distances
from src.utils import plot_kmeans_clustering

1 K-Means (7 Points)

K-Means is a widely used clustering algorithm in machine learning that partitions a dataset into K distinct, non-overlapping clusters. Its objective is to group similar data points together while keeping them as distinct as possible from other groups. The algorithm iteratively assigns data points to clusters and repositions cluster centers until convergence, minimizing the sum of squared distances between data points and their respective cluster centers.

The process begins by randomly initializing K cluster centroids in the feature space. Data points are then assigned to the nearest centroid based on a distance metric, often using Euclidean distance. After the initial assignment, the centroids are recalculated as the mean of all data points within each cluster. This process of assignment and centroid update continues until the centroids no longer significantly change or a predetermined number of iterations is reached. K-Means is efficient and scalable, making it suitable for large datasets, but its performance can be influenced by the initial choice of centroids and the determination of the optimal number of clusters (K), which can be a subjective challenge.

1.1 Performing K-Means “By Hand” (1 Point)

The plot below shows a toy dataset of 15 data points labeled A, B, C, …, O.

Perform K-Means with K=3 on the data shown above, taking points C, H, and M as the initial cluster centers! At the end of each iteration, list the positions of the cluster centers, as well as the set of pointshas belonging to each cluster. At the end, briefly discuss if the final clustering is satisfactory or not. There is no need for you to implement anything here.

Your Answer:
The final positions of the cluster centers are:
C(0, 1)
H(0, 0)
M(0, -1)
The set of points belonging to each cluster are:
C: A, B, D, E
H: F, G, I, J
M: K, L, N, O
The final clustering has been satisfactory in the sense that the cluster centers have remained at their initial positions, indicating that the given points can be well-represented by these centers.

1.2 Simple Implementation of K-Means (4 Points)

In this task, you implement your on K-Means clustering algorithm. But not to worry, this will be easier than you might think and we will guide you step by step through this process. Since we focus on the basic understanding and not on any optimization strategies, very few basic steps are needed to implement this basic but also very popular clustering algorithm.

First, let’s load the toy dataset we will use throughout the task so you can check your implementation after each step.

X = pd.read_csv('data/a4-kmeans-toy-data.csv').to_numpy()

plt.figure()
plt.scatter(X[:,0], X[:,1])
plt.show()

​
请添加图片描述

​

The code cell below contains the class MyKMeans you will complete in the following three subtasks. The input parameters for MyKMeans should be self-explanatory and are mimic the parameter names from sklearn.cluster.KMeans, so you can check out the documentation if anything is not clear.

class MyKMeans:
    
    def __init__(self, n_clusters=8, max_iter=300):
        self.n_clusters = n_clusters   # Number of cluster to be returned
        self.max_iter = max_iter       # Maximum number of iterations
        self.cluster_centers_ = None   # List of cluster centroids
        self.labels_ = None            # List of cluster labels for each data point
        self.n_iter_ = 0               # Number of iterations performed (<= max_iter)
        
        
    def initialize_centroids(self, X):
        ############################################
        ## To be completed for Task 1.2 a)
        ############################################
    
        # Pick the first centroid randomly
        c1 = np.random.choice(X.shape[0], 1)

        # Add first centroids to the list of cluster centers
        self.cluster_centers_ = X[c1]

        # Calculate and add c2, c3, ..., ck (we assume that we always have more unique data points than k!)
        while len(self.cluster_centers_) < self.n_clusters:

            # c is a data point representing the next centroid
            c = None

            #########################################################################################
            ### Your code starts here ###############################################################

            # Calculcate Euclidean Distances between data points and all centroids
            distances = np.array([np.linalg.norm(X - c, axis=1) for c in self.cluster_centers_])
            
            # Find distances between the data points to their NEAREST centroid
            distances = np.min(distances, axis=0)
                
            # Pick a random data point as next centroid according to the K-Means++ initialization
            probabilities = distances / distances.sum()
            c = X[np.random.choice(X.shape[0], 1, p=probabilities)]
    
            ### Your code ends here #################################################################
            #########################################################################################                

            # Add next centroid c to the array of already existing centroids
            self.cluster_centers_ = np.concatenate((self.cluster_centers_, c), axis=0)

    
    
    def assign_clusters(self, X):
        ############################################
        ## To be completed for Task 1.2 b)
        ############################################
        
        
        # Reset all clusters (i.e., the cluster labels)
        self.labels_ = None

        #########################################################################################
        ### Your code starts here ###############################################################    
            
        # Calculcate Euclidean Distances between data points and all centroids
        distances = np.linalg.norm(X[:, np.newaxis] - self.cluster_centers_, axis=2)

        # For each data point, identify it cluster id (which is of tange 0, 1, ..., k-1)
        self.labels_ = np.argmin(distances, axis=1)
            
        ### Your code ends here #################################################################
        #########################################################################################

    

    def update_centroids(self, X):
        ############################################
        ## To be completed for Task 1.2 c)
        ############################################        

        # Initialize list of new centroids with all zeros
        new_cluster_centers_ = np.zeros_like(self.cluster_centers_)

        for cluster_id in range(self.n_clusters):

            new_centroid = None

            #########################################################################################
            ### Your code starts here ###############################################################  

            # Identify all data points currently assigne to the cluster
            mask = self.labels_ == cluster_id

            # Get the mean of all samples in the cluster
            new_centroid = np.mean(X[mask], axis=0)
            

            ### Your code ends here #################################################################
            #########################################################################################

            new_cluster_centers_[cluster_id] = new_centroid  
            
        # Check if old and new centroids are identical; if so, we are done
        done = (self.cluster_centers_ == new_cluster_centers_).all()    
        
        # Update lest of centroids
        self.cluster_centers_ = new_cluster_centers_

        # Return TRUE if the centroids have not changeg; return FALSE otherwise
        return done
    
    
    def fit(self, X):
        # Initialize centroids
        self.initialize_centroids(X)
        # Perform assignments and updates until convergences
        self.n_iter_ = 0
        for _ in range(self.max_iter):
            # Update iteration counter
            self.n_iter_ += 1
            # Assign cluster
            self.assign_clusters(X)
            # Update centroids
            done = self.update_centroids(X)
            if done:
                break
        return self
1.2 a) Initializing Centroids (2 Points)

As we learned in the lecture, K-Means is rather sensitive to the initialization of the clusters. The most common initialization method is K-Means++ (see lecture slides). Note that K-Means++ is non-deterministic as it picks the next centroids based on probabilities depending on the distances between the data points and the existing centroids. You will implement the K-Means++ initialization in this task.

Implement method initialize_centroids() below to calculate the initial centroids based on K-Means++! Hint: Notice that we have already imported the method euclidean_distances() for you. Also, check out the methods np.random.choice() and np.min() as they might come in very handy. You are not required to use any of those methods, but they can arguably make your life so much easier.

You can use the code cell below you check your implementation:

# Make the randomness "predictable" so the result is always the same
# (if you remove this line, the output will change for each run)
np.random.seed(0) 

my_kmeans = MyKMeans(n_clusters=3)
my_kmeans.initialize_centroids(X)

print(my_kmeans.cluster_centers_)
[[ 5.19  4.27]
 [ 6.07 -7.61]
 [ 3.53  7.67]]

The output of previous code cell should look something like:

[[  5.19   4.27]
 [  7.72  -6.01]
 [ -4.66 -11.3 ]]

an array with k = 3 k=3 k=3 rows – one for each centroid – and each row is an array with 2 coordinates since our dataset is just 2-dimensions. If you change the value for k, the shape of the array will change accordingly.

1.2 b) Assigning Data Points to Clusters (1 Point)

Implement method assign_clusters() to assign each data point to its nearest centroid! Hint: You may want to check np.argmin() as well as consider the imported method np.random.choice() again.

The method assign_clusters() needs update self.labels_ which is a 1-dimensional array of length N N N (number of data points). Each element in self.labels_ is a value ranging from 0 0 0 to ( k − 1 ) (k-1) (k−1) indicating to which cluster id a data point belongs to. For example, if self.labels_ = [1, 0, 2, 2, 1], the first and the last data point belong the same cluster. The second data point forms its own cluster; the third and forth data points form the third cluster (here k = 3 k=3 k=3)

You can use the code cell below you check your implementation:

# Make the randomness "predictable" so the result is always the same
# (if you remove this line, the output will change for each run)
np.random.seed(0)

my_kmeans = MyKMeans(n_clusters=3)
my_kmeans.initialize_centroids(X)
my_kmeans.assign_clusters(X)

print(my_kmeans.labels_)
[1 1 2 1 2 1 2 1 2 1 0 2 2 1 1 0 2 0 0 1 0 0 1 2 1 1 0 1 1 1 0 2 0 1 0 0 0
 0 0 1 2 1 2 1 0 1 2 0 1 1 0 1 0 1 1 0 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 1 2 0
 0 0 1 1 0 0 1 0 2 0 1 2 0 1 0 0 0 0 1 1 0 2 0 1 1 0]

The output of the code cell above should be:

[2 2 0 1 0 1 0 1 0 1 0 0 0 1 2 0 0 0 0 1 0 0 2 0 2 2 0 2 2 1 0 0 0 1 0 0 0
 0 0 1 0 1 0 1 0 2 0 0 2 2 0 2 0 1 1 0 1 0 0 0 0 0 0 1 1 1 0 0 0 0 1 2 0 0
 0 0 2 2 0 0 2 0 0 0 1 0 0 2 0 0 0 0 1 2 0 0 0 2 2 0]

Recall that we have 100 data points and set k = 3 k=3 k=3. Hence, the length of the array is 100 and each element is either 0, 1, or 2, representing the cluster id/label. Note that the cluster id has no intrinsic meaning, it’s only important that points in the same cluster have the same id/label. For example, the result [1, 1, 0, 2, 1, 2] would represent the same clustering as [0, 0, 2, 1, 0, 1].

1.2 c) Updating the Centroids (1 Point)

After the assignment of the data points to clusters, all centroids need to be moved to the average of their respective clusters. Note that the centroids might not change because the assignment made no changes to the clusters and K-Means is done. We already handle this part in the given skeleton of the implementation.

Implement update_centroids() to update the centroids (i.e., cluster center) with respect to the new cluster assignments! Hint: As usual, we recommend making good use of numpy, or maybe sklearn, including methods such as np.where() and np.mean().

You can use the code cell below you check your implementation:

# Make the randomness "predictable" so the result is always the same
# (if you remove this line, the output will change for each run)
np.random.seed(0)

my_kmeans = MyKMeans(n_clusters=3)
my_kmeans.initialize_centroids(X)
my_kmeans.assign_clusters(X)
my_kmeans.update_centroids(X)

print(my_kmeans.cluster_centers_)
[[ 5.35925  2.61125]
 [ 1.332   -7.79325]
 [ 3.5225   9.6595 ]]

The output of the code cell above should be:

[[ 4.747       4.96066667]
 [ 7.7005     -6.3995    ]
 [-5.0365     -9.187     ]]

Again, the output reflects our setting of k = 3 k=3 k=3 and our 2-dimensional dataset. Of course, the new centroid locations should differ from the initial centroid locations in 1.2 a).

Putting it all together (nothing for you to do here!) With the initialization of the centroids, the assignment to cluster, and the update of the centroids in place, we have everything in place to perform K-Means++ over a dataset X given a choice for k. The method fit() below performs K-Means++ using your implementations of the methods initialize_centroids(), assign_clusters(), and update_centroids(). Note that we can exit the main loop once there is no more change in the cluster assignments; if all fails, the algorithm stops after max_iter iterations.

np.random.seed(0) 

my_kmeans = MyKMeans(n_clusters=3).fit(X)

print('Number of iterations: {}\n'.format(my_kmeans.n_iter_))
print('Final cluster centers:\n{}\n'.format(my_kmeans.cluster_centers_))
print('Final cluster labels:\n{}\n'.format(my_kmeans.labels_))
Number of iterations: 6

Final cluster centers:
[[ 5.43179487  1.65076923]
 [ 0.76486486 -8.04243243]
 [ 4.08166667  9.12916667]]

Final cluster labels:
[1 1 2 1 2 1 2 1 2 1 0 2 2 0 1 2 2 0 0 1 0 0 1 2 1 1 0 1 1 1 0 2 0 1 0 0 0
 0 0 0 2 1 2 0 0 1 2 0 1 1 2 1 0 1 1 0 1 0 0 0 0 2 2 1 1 1 2 0 2 0 1 1 2 2
 0 0 1 1 0 2 1 0 2 0 1 2 0 1 0 0 0 0 1 1 0 2 0 1 1 0]

The output of the code cell above should reflect the output we have seen for 1.2 b) and 1.2 c), assuming you have not changed the default parameters for the random seed and for the number of clusters k k k.

Visualization (nothing for you to do here!) We provide you with the auxiliary method plot_kmeans_clustering(); you can checkout src.utils to have a look at the code of the method. Feel free to go back and run MyKMeans with different values for k k k (visually we could already tell that k = 5 k=5 k=5 is probably the best choice) and/or different random seeds (or not setting any seed at all). Just note that the given expected outcomes will no longer match for other values for k k k and other seeds. But you can always visualize the result to assess whether the results look meaningful.

plot_kmeans_clustering(X, my_kmeans.labels_, my_kmeans.cluster_centers_)

​

​

You have now completed the implementation of K-Means (more specifically, K-Means++). Well done!

1.3 Questions about K-Means (2 Points)

In the table below are 6 statements that are either True or False. Complete the table to specify whether a statement is True or False, and provide a brief explanation for your answer (Your explanation is more important than a simple True/False answer).

This is a markdown cell. Please fill in your answers for (1)~(6).

No.StatementTrue or False?Brief Explanation
(1)When using K-Means++, then centroids are always at the position of existing data pointsFalseIn K-Means++, only the initial centroids are chosen from the existing data points.
(2)K-Means++ ensures that the result will not include any empty clusters.FalseK-Means++ initialization helps reduce the chances of empty clusters by probabilistically selecting initial centroids. However, it does not guarantee the absence of empty clusters in all cases.
(3)K-Means, independent of the initialization method, will always converge to a local minimumFalseK-Means is sensitive to the initial placement of centroids, and different initializations may lead to different local minima. However, convergence to a global minimum is not guaranteed.
(4)K-Means++ will always converge to the global optimum.FalseK-Means++ improves the initialization step, but it does not guarantee convergence to the global optimum.
(5)K-Means++ initialization is more costly than a random initialization of the centroids but generally converges faster.TrueK-Means++ initialization is generally more costly than random initialization because it involves a single pass through the dataset. And it can lead to faster convergence during the subsequent iterations of the K-Means algorithm.
(6)K-Means is insensitive to data normalization/standardization – that is, for the same k k k and the same initial centroids, K-Means will yield the same clusters where the data is normalized/standardized or not.FalseThe essence of K-means is a data partitioning algorithm based on Euclidean distance. Dimensions with high mean and variance will exert a decisive influence on the clustering of the data.

2 Hierarchical Clustering (AGNES) (3 Points)

Agglomerative clustering is a hierarchical clustering technique that starts by assigning each data point to its own cluster and then iteratively merges the closest clusters together based on a similarity measure. The process continues until all data points belong to a single cluster or until a predefined stopping criterion is met. This method creates a hierarchical tree or dendrogram that illustrates the merging process and allows exploration of different numbers of clusters.

At the beginning of the process, each data point is considered a separate cluster. Then, pairs of clusters with the smallest distance or highest similarity are merged at each step, creating larger clusters. The choice of distance metric (such as Euclidean distance or others depending on the data type) and the linkage criteria (defining how to measure the distance between clusters) significantly impact the clustering outcome. Agglomerative clustering does not require specifying the number of clusters beforehand, making it flexible for exploring the structure of the data at different granularity levels. However, its computational complexity increases with the number of data points, making it less efficient for very large datasets.

2.1 Interpreting Dendrograms (2 Points)

We saw in the lecture that dendrograms are a meaningful way to visualize the hierarchical relationships between the data points with respect to the clustering using AGNES (or any other hierarchical clustering technique). Properly interpreting is important to get a correct understanding of the underlying data.

Below are the plots of 6 different datasets labeled A-F. Each dataset contains 30 data points, each with two dimensions.

Below are 6 dendrograms labeled 1-6. These dendrograms show the clustering using AGNES with Single Linkage for the 6 dataset above, but in a random order.

Find the correct combinations of datasets and dendrograms – that is, find for each dataset the dendrogram that visualizes the clustering using AGNES with Single Linkage! Give a brief explanation for each decision! Complete the table below! (The last line shows an example.)

DatasetDendrogramBrief Explanation
A6The data can be relatively evenly divided into two categories.
B3The data is uniformly distributed and clustering is not effective.
C2The data has two dispersed clusters.
D4The data can be relatively evenly divided into three categories.
E1The data can be relatively evenly divided into three or four categories.
F5The data has one dispersed cluster.>
X9The dataset plot looks like a face and the dendrogram looks like a hat (please come up with better explanations 😃 !)

2.2 Comparing Linkage Methods (1 Point)

Let’s assume we have a dataset consisting of all integer numbers from 1 to 1,000 (i.e., we have a 1-dimensional dataset. We now want to cluster these numbers using AGNES, with the Euclidean distance as our distance measure. If 2 clusters have the same distance, we break the tie by selecting the two clusters that contain the smallest number!

We cluster this dataset using the three Linkage methods Single Linkage and Complete Linkage. For each of the two Linkage methods, what are the sizes of the last 2 clusters to be merged – that is, what is the number of elements (here: the integers) in the 2 clusters at the root of the resulting dendrograms. Provide a brief explanation for your answers!

Your Answers:

Linkage MethodSize of 1st clusterSize of 2nd clusterBrief explanation
Single Linkage22In Single Linkage, the merging process is driven by the minimum distance between individual points. The last two clusters to be merged will have the smallest number of elements, which is 2 in this case.
Complete Linkage9991In Complete Linkage, the merging process is driven by the maximum distance between points. The last two clusters to be merged will have one cluster with a single element (smallest number) and another cluster with the remaining elements.

如何处理动态语言(Python / JS)的“隐形”调用链? 本文揭示动态语言(Python/JS)中静态AST解析导致调用链“断链”的核心问题,提出通过运行时追踪补全图谱的解决方案。基于Code-Graph-RAG的cgr trace机制,分别利用pytest插件与V8 Profiler捕获真实调用路径,将动态边合并至静态图谱,并在权重体系中提升动态边优先级。实践表明,该方法可显著提升图谱覆盖率,实现“结构+行为”双视角理解代码,为MCP与Rerank系统提供可靠支持。 阅读详情

相关推荐

2024.6.15丨基于VFDB数据库的致病菌毒力因子注释实战指南

本文提供了一份基于VFDB数据库进行致病菌毒力因子本地化注释的实战指南。详细介绍了从环境准备、DIAMOND工具安装、VFDB数据库选择与构建,到核心比对操作及结果解读与过滤的全流程。重点阐述了本地化分析相较于在线工具在速度、稳定性和批量处理上的优势,旨在帮助微生物基因组研究人员高效、精准地识别致病菌的关键毒力因子。

weixin_29220405的博客 270

AI全栈实战 | 3.9-01 爬虫入门:requests 加 BeautifulSoup 三分钟跑通,但 90% 的人栽在这 4 个“礼貌“问题上

⚠️:本文内容仅用于。请遵守目标站点的服务条款与相关法律法规,不得对目标服务造成负担,不得采集、传播个人隐私数据。技术是中性的,边界在你手里。爬虫的入门技术(requests 发请求 + BeautifulSoup 解析)三分钟就能学会。真正区分"会用爬虫"和"会做爬虫的人"的,是这篇我们跑通"请求→解析→存储"的最小闭环,然后重点把"合规与礼貌"这根弦给你绷上。

源码获取 | 运行部署 | 定制二开修改,如果回复不及时请耐心等待,请见谅。 406

C语言——利用矩阵LU分解法求逆、行列式

本章介绍了LU分解法,以及如何利用LU分解法求逆、行列式,针对每个公式、原理、代码进行了详细介绍,希望可以给大家带来帮助。

王元笙 1万+

从一段视频到可漫游的 4D 有声场景:思路拆解与最小复现手记

只需一段手机视频,你就能生成可"走进去"的 4D 有声场景:转头时狗叫声方向随之变化,走近时声音更清晰。本文拆解 Video-to-4DAVScene 的核心思路,手把手带你用几十行 Python 搭出最小管线,把视频中的运动物体变成带空间位置的声源,并附上三个真实踩坑的排障经验,代码可直接跑。🎧

helloagent的博客 235

基于深度学习的道路裂缝检测识别研究(开题报告)

具体而言,将本研究提出的模型与其他先进的道路裂缝检测算法在相同的数据集上进行对比实验,通过对比实验结果,分析不同算法在准确率、召回率、F1值等指标上的优劣,以及在实际应用中的表现。通过对综述论文的学习了解,对计算机视觉、多模态相关领域的基础进行简要介绍,并在跨模态行人重识别研究领域归纳国内外研究现状和发展趋势,明确当前面临的问题和挑战,并针对当前存在的问题展开后续研究。第二,研究解决该问题的途径和方法。基于深度学习的道路裂缝检测识别研究,旨在通过构建和优化深度学习模型,实现对道路裂缝的自动识别和定位。

毕业作品网站 3829

基于车辆运动学的规划算法 - Hybrid A*/ State Lattice Planning (前置知识:自行车模型、Dubins、Reeds Shepp、多项式曲线、螺旋曲线)

本文将按顺序讲解基于车辆运动学的规划算法,以及需要的前置知识:自行车模型、Dubins和Reeds Shepp曲线、多项式曲线和螺旋曲线

BigDavid123的博客 4859

【每天一个 Python 小案例30】Python 基础知识综合小项目:我的工具盒

作为系列收官,本篇把前 29 篇的知识点合成一个能直接用的命令行工具"我的工具盒":计算器(用 ast 解析表达式,不碰 eval)、单位换算与温度转换(一张换算表 + 特例分支)、记账与分类统计(Decimal + JSON 持久化)、以及用"字典当命令表"把菜单和业务逻辑解耦的主循环。文中对比了 eval 的安全隐患与 ast 白名单的做法,解释了 lambda 闭包在字典里的写法与晚绑定陷阱,并在最后给出整个系列的知识地图,把变量、数据结构、控制流、函数、类、异常、文件、标准库八块内容对应到具体篇目。

xinjiyaya的博客 426

RK3588平台-ES8388音频驱动调试与设备树配置实战

本文详细解析了在RK3588平台上调试ES8388音频驱动的实战过程。内容涵盖Linux音频驱动的三层架构(Machine、Platform、Codec),并重点提供了设备树(DTS)的完整配置示例,包括I2C节点、声卡节点及音频路由设置。文章还分享了驱动加载验证、amixer调试命令以及常见问题(如无声、变调)的排查思路,旨在帮助开发者快速完成RK3588与ES8388的音频系统集成。

mango的博客 806

详解Python条件语句

在 Python 中,if...else 是一种条件语句,可以根据给定的条件执行不同的操作。这个语句通常用于控制程序的流程。

2601_96798737的博客 207

YOLOv12创新改进 | 全网独家创新篇、小目标检测改进 | AAAI 2025 | 引入HS-FPN中的HFP和SDP创新点,从频域增强小目标特征,淘汰FPN进行升级,助力YOLOv12有效涨点

本文提出了HS-FPN(高频和空间感知特征金字塔网络),通过HFP(高频感知)模块增强小目标特征,SDP(空间依赖感知)模块捕获像素间空间依赖关系。实验在AI-TOD等小目标数据集上验证了该方法的有效性,相比FPN显著提升检测性能。文章详细介绍了HS-FPN的网络结构、核心代码实现及在YOLOv12中的应用方法,并提供多种改进版本的yaml配置文件,为小目标检测任务提供了有效的解决方案。

Ai缝合怪、助力小伙伴高效发论文 336

MAX30102心率血氧传感器原理图设计,已量产(e-Health传感器)

在最近的便携健康监测设备项目中,我们采用了集成算法的 MAX30102 心率血氧模块 —— 这类带内置 MCU 算法的传感器能直接输出心率 / 血氧数值,大幅降低了主控资源占用。但硬件电路的稳定性直接决定了 PPG 信号的采集精度,下面结合实际项目里的原理图,拆解下这个模块的设计细节。

不脱发的程序猿 1278

Python3 协程:异步编程的核心机制与实战

协程是解决I/O密集型任务等待瓶颈的高效机制,相比线程更轻量、无锁开销。从yield到async/await的演进,使异步编程语义清晰、易于理解。通过async/await可实现并发执行多个任务(如gather、create_task),显著提升网络请求、爬虫等场景性能。关键在于使用异步库(如aiohttp)替代同步库,避免阻塞事件循环。合理控制超时与并发数,才能发挥协程最大优势。

Lxn2zh的博客 159

使用GBIF获取生物多样性数据与GIS的结合

随着全球生物多样性的重要性日益凸显,越来越多的研究人员和保护机构开始利用地理信息系统(GIS)来分析和可视化生物多样性数据。GBIF(全球生物多样性信息设施)作为一个全球性的生物多样性数据库,提供了大量的物种分布和分类信息,为研究人员和保护工作者提供了宝贵的数据资源。本文将介绍如何使用GBIF API获取生物多样性数据,并将其与GIS技术相结合,以便更好地理解和研究生物多样性。利用GIS的强大功能,我们可以在地理空间上可视化物种分布、分析物种多样性的空间格局,并为保护生物多样性提供科学依据。

BnxBackend的博客 1763

torch.compile 差异仅 1e-6,边界样本预测为何翻转

torch.compile 加速后输出与 eager 不一致,部分预测翻转。逐层对比与 graph break 分析定位到动态分支翻转根因。容差回归仅适用于无分支翻转场景,零容忍场景应禁用编译。

昨日种种,皆成今我。今日种种,皆成新我。 159

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

二进制木马免杀-Python 分离免杀与 Web 挂马

二进制木马免杀-Python 分离免杀与 Web 挂马

2503_94637398的博客 268

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级 备考:莫队算法离线区间查询详解

备赛进行时:第十八届蓝桥杯软件赛报名已于 2026-10-08 10:00 开启、12-18 14:00 截止,省赛定在 2027-04-10(C/C++·Python 程序设计 9:00–13:00);中国电子学会 2026 年 12 月软件编程(C/C++ 一级至十级、Python 一级至六级)考级报名 9/23–12/2 16:00、统考 12-12;全国青少年信息素养大赛 2026—2027 赛季算法应用主题赛也已进入复盘练兵窗口。

IT_Scratch的博客 137

【Python】国家中小学智慧教育平台电子教材批量下载与 PDF 合成实战

成果:两本语文电子课本(一年级上册 118 页 / 23MB、三年级上册 130 页 / 30.3MB),合计 248 页、约 54MB,单本下载加合成 40~60 秒,PDF 页数校验全部通过。经验教训SPA 站点的数据接口优先从 bundle 里挖,比抓页面稳得多;资源链接要按 private/public 分组看待,只取平台公开部分;页数、目录名这类“可推断”的信息,永远用实际响应验证一次;受限环境里“能不能跑浏览器”要在方案定稿前确认。后续计划:这版 PDF 是图片版,没有文字层;

木头大左的博客 137

魔塔社区微调训练Qwen2-1.5B-Instruct模型并烧录到‌RK3568开发板教程

本文基于Ubuntu 22.04 + CUDA 13.0.3环境,使用LLaMA-Factory框架对Qwen2-1.5B-Instruct模型进行LoRA微调,训练儿童故事生成专用模型。通过配置qwen模板、制作alpaca格式数据集、执行sft训练并合并LoRA权重,最终将模型转换为GGUF格式,并量化为Q4_K_M以适配RK3568嵌入式平台。全程支持国产镜像加速下载与显存优化,实现高效轻量化部署。

浅清秋慕夏的博客 186

【回眸】DeepSeek V4.1 Flash 快速上手与实战

本文介绍如何高效本地部署开源大模型,通过现代化工具链实现分钟级环境搭建。聚焦显存优化、一键安装、代码调用与多轮对话实现,解决“显存不足”“连接超时”等痛点,提供参数调优与结构化输出技巧,助力开发者在离线场景下快速构建稳定、高效的本地推理系统。

啤酒鸭的物联网开发记录博客 223

智叟云集-手机证据抓取系统的工程结构与应用入口

本文系统阐述手机证据抓取系统的工程结构与应用入口,涵盖四大层面:工程目录划分(Android、Python服务、Web页面、测试与构建工具);Android组件通过Manifest声明可启动页面,主界面由MainActivity管理;Python服务通过run.py解析参数并启动FastAPI应用,支持远程访问;浏览器页面采用HTML/CSS/JS分离架构,静态资源通过路径关联,实现动态交互。各模块分工明确,协同构建可运行的采集系统。

2301_77178996的博客 232

Java Arrays.asList 常见坑详解|UnsupportedOperationException、数组联动、基本类型 bug

解析 Arrays.asList 常见开发陷阱,演示 UnsupportedOperationException、底层数组引用共享、基本类型数组问题,区分 Arrays 内部 ArrayList 与 java.util.ArrayList,给出数组转 List 的各种场景正确代码。

weixin_42617033的博客 473

利用python中matplotlib.pyplot库绘制图

plt.plot(x,y) # x,y是每个点的坐标,plot()把每个点按顺序画折线。plt.subplots(2,2)表示绘制2*2的子图布局,axs[0,0]表示在第0行第0列绘制子图...coordinates_i[:,0]表示获取每一行(每一个spot)的第0列(x坐标)coordinates_i[:,1]表示获取每一行(每一个spot)的第0列(y坐标)plot.subplot(2,2,1) 表示子图布局是2*2的,开始绘制第一个。也可以导入数据绘制。可以设置color属性,设置颜色。

qq_46147236的博客 102

Spring Boot 自动配置原理

Spring Boot 自动配置由 @EnableAutoConfiguration 导入选择器,读取 jar 中 .imports 候选清单,经去重、排序、排除后逐类做条件判断,通过才注册 Bean。延迟导入让用户 Bean 优先,@ConditionalOnMissingBean 使默认配置让位。失效时查清单和 Negative matches。

2401_89855466的博客 377

【随笔】KV缓存量化:省下的显存,要付出多少数值误差

用可运行量化器解释位宽、比例信息、分组和离群值的关系,核算KV缓存实际载荷,并给出Transformers配置与容量、延迟、质量验收方法。

code2cat的博客 455

【每天一个 Python 小案例29】Python 实现商品购物车

本篇实现一个购物车:商品目录、加入商品、修改数量、移除商品、查看小计、计算满减与 VIP 折扣、结算扣库存。核心设计是"目录与购物车分离"——目录存商品主数据,购物车只存 {商品编号: 数量};金额一律用 Decimal 并做 ROUND_HALF_UP 舍入。折扣部分讲清阶梯满减的匹配顺序(阈值从高到低、命中即停)与叠加顺序(先满减、后打折),并用一次完整结算演示 706 元如何变成 613.70 元。

xinjiyaya的博客 212

Python的字典

Python字典是存储键值对的数据结构,通过键(key)快速查找对应的值(value)。可使用{}定义,支持增删改查操作:通过dict[key]查询或修改值,get()方法安全获取并设置默认值,del dict[key]删除键值对,keys()、values()和items()用于遍历。items()结合双变量循环可高效遍历所有键值对,提升代码可读性与灵活性。

qq_43010954的博客 197
上一篇: COMP1921 Resit Asssignment
下一篇: FIT1008-S2-2024-A1
todcode
博客等级 码龄7年 359粉丝 108原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值