Python是一種極受歡迎的編程語(yǔ)言,其應(yīng)用廣泛,特別是在數(shù)據(jù)科學(xué),機(jī)器學(xué)習(xí)和人工智能領(lǐng)域。以下是Python最常應(yīng)用的領(lǐng)域:
Web開發(fā):
# 創(chuàng)建一個(gè)簡(jiǎn)單的Web服務(wù)器
from http.server import HTTPServer, BaseHTTPRequestHandler
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(b"Hello, world!")
httpd = HTTPServer(('localhost', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
數(shù)據(jù)科學(xué):
# 導(dǎo)入pandas庫(kù)并讀取文件
import pandas as pd
df = pd.read_csv('data.csv')
print(df.head())
機(jī)器學(xué)習(xí):
# 導(dǎo)入scikit-learn庫(kù)并加載數(shù)據(jù)集
from sklearn import datasets
iris = datasets.load_iris()
# 劃分?jǐn)?shù)據(jù)集為訓(xùn)練集和測(cè)試集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
# 導(dǎo)入邏輯回歸模型并擬合數(shù)據(jù)
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(max_iter=1000)
clf.fit(X_train, y_train)
# 預(yù)測(cè)測(cè)試集
y_pred = clf.predict(X_test)
# 導(dǎo)入評(píng)估指標(biāo)并評(píng)估模型
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print(accuracy)
人工智能:
# 導(dǎo)入PyTorch庫(kù)并定義神經(jīng)網(wǎng)絡(luò)
import torch
class Net(torch.nn.Module):
def __init__(self, n_input, n_output):
super().__init__()
self.linear1 = torch.nn.Linear(n_input, 64)
self.linear2 = torch.nn.Linear(64, n_output)
def forward(self, x):
x = torch.relu(self.linear1(x))
x = self.linear2(x)
return x
# 導(dǎo)入數(shù)據(jù)集并定義優(yōu)化器和損失函數(shù)
data = torch.randn(100, 10)
target = torch.randn(100, 1)
net = Net(10, 1)
optimizer = torch.optim.SGD(net.parameters(), lr=0.1)
criterion = torch.nn.MSELoss()
# 訓(xùn)練神經(jīng)網(wǎng)絡(luò)
for i in range(100):
optimizer.zero_grad()
output = net(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
# 預(yù)測(cè)輸出值
test_data = torch.randn(10, 10)
output = net(test_data)
print(output)