본문 바로가기

카테고리 없음

Python #8

In this session, we'll cover some advanced Python topics, including concurrency with threading and multiprocessing, an introduction to machine learning with scikit-learn, and an overview of web development with Flask.

Concurrency in Python

Concurrency allows you to perform multiple operations at the same time. Python provides several modules to handle concurrency, including threading and multiprocessing.

Threading

The threading module is used for running tasks concurrently in the same process.

import threading

def print_numbers():
    for i in range(5):
        print(i)

# Create a thread
thread = threading.Thread(target=print_numbers)
thread.start()

# Wait for the thread to finish
thread.join()

Multiprocessing

The multiprocessing module allows you to run tasks in parallel across multiple CPU cores.

from multiprocessing import Process

def print_numbers():
    for i in range(5):
        print(i)

# Create a process
process = Process(target=print_numbers)
process.start()

# Wait for the process to finish
process.join()

Machine Learning with Scikit-learn

Scikit-learn is a popular library for machine learning in Python. It provides simple and efficient tools for data mining and data analysis.

Basic Example: Linear Regression

from sklearn.linear_model import LinearRegression
import numpy as np

# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([2, 4, 6, 8, 10])

# Create a linear regression model
model = LinearRegression()
model.fit(X, y)

# Predict new values
predictions = model.predict(np.array([[6], [7]]))
print(predictions)  # Output: [12. 14.]

Web Development with Flask

Flask is a lightweight web framework for building web applications in Python.

Basic Flask Application

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

Running the Flask App

To run the Flask application, save the code to a file (e.g., app.py) and execute it:

python app.py

Then visit http://127.0.0.1:5000/ in your web browser to see the output.

These advanced topics will help you leverage Python's capabilities for concurrent programming, machine learning, and web development.