Python Syntax
Recommended Reading : 【Python】 Python Table of Contents
1. Overview
2. Syntax
3. Library
a. R Overview
1. Overview
⑴ Advantage 1. Easy to implement backend in app development, etc.
⑵ Advantage 2. Well-developed deep learning tools
⑶ Advantage 3. Various applications possible based on open community
⑷ Advantage 4. Excellent data visualization
2. Syntax
⑴ Python can return multiple values simultaneously
⑵ %%time: Outputs running time
⑶ pass or ...: Used when code is syntactically required but no action is needed.
⑷ yield returns values one at a time when needed, rather than all at once
⑸ You can write multi-line code by using backspace \ for line breaks
⑹ A single-line string is represented by “~” or ‘~’, and a multi-line string is represented by “””~””” or ‘’’~’’’
⑺ adata.var_names=[i.upper() for i in list(adata.var_names)]
① Meaning: In adata.var_names, each i in list(data.var_names) is stored in uppercase
⑻ if issparse(counts.X):counts.X=counts.X.A
① Meaning: If counts.X is a sparse matrix, the value of counts.X.A is assigned to counts.X
⑼ pd.DataFrame([(str(i),str(j)) for i in range(4) for j in range(i+1, 4)])
0 1
0 0 1
1 0 2
2 0 3
3 1 2
4 1 3
5 2 3
⑽ Matrix Operations
① For matrices defined with NumPy, the
*and**operators perform element-wise multiplication (and element-wise power). → In this case, use the@operator to indicate matrix multiplication.
② For matrices defined with SymPy (
Matrix), the*and**operators mean matrix multiplication and matrix power, respectively.
○ Using Python (NumPy)
import numpy as np
# Define two matrices
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Print matrices
print("Matrix A:")
print(A)
print("\nMatrix B:")
print(B)
# Matrix multiplication
result = np.dot(A, B)
## Alternatively, result = A @ B
print("\nNumPy matrix multiplication result:")
print(result)
○ Using Python (SymPy)
from sympy import Matrix, init_printing
# Initialize LaTeX-style printing
init_printing()
# Define two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 6], [7, 8]])
# Print matrices
print("Matrix A:")
display(A)
print("Matrix B:")
display(B)
# Matrix multiplication
result = A * B
print("SymPy matrix multiplication result:")
display(result)
3. Library
⑴ NumPy
① A core library that enables fast numerical computation (matrix operations, vector operations) based on multidimensional arrays (
ndarray).
② Broadcasting
○ A feature in NumPy that allows operations between arrays of mismatched dimensions
○ A small array (as long as it has a dimension of 1) is automatically expanded to match the larger array’s shape, and then the operation is performed
○ Data is not physically copied to match the small array to the large array
# Shape of `exp_log_mu`: (2257, 6)
# Shape of `theta_mn`: (6, 13344)
exp_log_mu_expanded = exp_log_mu[:, :, np.newaxis] # Shape: (2257, 6, 1)
theta_mn_expanded = theta_mn[np.newaxis, :, :] # Shape: (1, 6, 13344)
result = exp_log_mu_expanded * theta_mn_expanded # Shape: (2257, 6, 13344)
⑵ Pandas
① Handles tabular data (
DataFrame) easily and is strong for data cleaning/preprocessing (handling missing values, filtering, grouping).
⑶ Matplotlib
① Used to visualize data distributions or patterns by drawing graphs (line plots, bar charts, scatter plots, etc.).
⑷ Scikit-learn (skimage)
① Provides traditional machine learning algorithms (classification/regression/clustering) and evaluation tools (cross-validation, performance metrics).
⑸ TensorFlow
① Allows training and deployment of deep learning models using a computation-graph-based approach; used for large-scale training and production deployment.
② Developed by Google’s AI team for machine learning and deep learning purposes.
③ Released in November 2015.
⑹ PyTorch
① Based on a dynamic computation graph, making implementation intuitive; widely used in research/experimentation to quickly develop and train deep learning models.
② Developed by Facebook’s artificial intelligence research team.
③ First released in 2016 and stabilized in April 2019.
④ Used in various fields, including natural language processing.
⑤ Highly flexible, so it is widely used in fundamental and core technology research.
⑺ SciPy
① Offers advanced mathematical/scientific computing features (optimization, statistics, signal processing), used for numerical computation in modeling and analysis.
⑻ OpenCV
① An image/video processing library used for preprocessing before tasks like object detection (filtering, contour detection, feature extraction).
⑼ NLTK
① Provides basic NLP tools (tokenization, morphological analysis, corpus processing) and is commonly used for education and introductory practice.
⑽ Transformers (Hugging Face)
① Makes it easy to load pretrained language models like BERT and GPT and apply them to NLP tasks such as classification, summarization, and translation.
⑾ spaCy
① A fast, production-oriented NLP library that efficiently performs named entity recognition (NER), part-of-speech tagging, and dependency parsing.
⑿ JAX
① A library that enables high-performance numerical computing and deep learning in Python.
② JaxGCRL only supports older jaxlib versions.
③ Jax does not support GPU usage on Windows. (ref)
Input: 2024.04.30 13:41