jupyter notebook
就能启动服务,浏览器会自动打开主界面。主界面左边是文件列表,右边可以新建笔记本或者文件夹。新建笔记本时记得选 Python 内核,这是最常用的。刚打开的笔记本是空的,里面有一个个的单元格,默认是代码单元格,咱可以在里面写 Python 代码,按 Shift + Enter
就能运行,运行结果会直接显示在单元格下方。# 一级标题
,运行后就是大大的标题了。另外,Jupyter Notebook 支持实时保存,不用担心代码丢失,不过养成随手保存的习惯总是好的。FuncAnimation
函数,指定更新数据的函数,就能让折线随着数据变化动起来。先导入必要的库:import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
fig, ax = plt.subplots()
x_data, y_data = [], []
line, = ax.plot([], [], 'b-')
def update(frame):
x_data.append(frame)
y_data.append(np.sin(frame * 0.1))
line.set_data(x_data, y_data)
ax.relim()
ax.autoscale_view()
return line,
ani = FuncAnimation(fig, update, frames=np.linspace(, , ), interval=)
plt.show()
pip install plotly
就行。用 Plotly 画动态柱状图,先准备数据:import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.bar(df, x="gdpPercap", y="country", color="continent",
title="GDP per Capita by Country (2007)",
labels={"gdpPercap": "GDP per Capita", "country": "Country"})
fig.show()
,在 Jupyter Notebook 里会直接渲染出交互式的图表,鼠标移到柱子上就能看到具体数据,还能点击图例显示或隐藏某个大洲的数据,特别方便。pip install bokeh
后,咱来画一个动态更新的散点图。先创建数据来源:from bokeh.driving import linear
from bokeh.plotting import figure, show, ColumnDataSource
source = ColumnDataSource(data=dict(x=[], y=[]))
p = figure(x_range=(-, ), y_range=(-, ), tools="", toolbar_location=None)
p.scatter('x', 'y', size=, source=source)
linear
装饰器让数据按线性变化:@linear()
def update(step):
x = np.linspace(-, , )
y = np.sin(x + step/)
source.data = dict(x=x, y=y)
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
def bk_worker():
server = Server({'/': Application(FunctionHandler(update))}, port=)
server.start()
server.io_loop.add_callback(show, p)
server.io_loop.start()
import threading
threading.Thread(target=bk_worker).start()
df.isnull().sum()
就能看出每列有多少缺失值。处理缺失值的方法有很多,数值型数据可以用均值、中位数填充,分类数据可以用众数填充,或者直接删除缺失太多的行或列。然后是数据清洗,比如去除重复数据,用 df.drop_duplicates()
就行。还有数据转换,分类数据需要转换成数值型,常用的方法有独热编码(One - Hot Encoding)和标签编码(Label Encoding),可以用 pd.get_dummies()
或者 LabelEncoder
来处理。StandardScaler
,归一化用 MinMaxScaler
。对于时间序列数据,可以提取年、月、日、小时等特征,对于文本数据,可以用词袋法(Bag - of - Words)、TF - IDF 等方法转换成特征向量。另外,还可以做特征组合,比如将两个数值型特征相乘或相加,生成新的特征。train_test_split
函数:from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=, random_state=)
model.fit(X_train, y_train)
cross_val_score
函数计算准确率、精确率、召回率等指标。GridSearchCV
和 RandomizedSearchCV
来实现。比如对随机森林的 n_estimators
、max_depth
、min_samples_split
等参数进行网格搜索:from sklearn.model_selection import GridSearchCV
param_grid = {
'n_estimators': [, , ],
'max_depth': [None, , , ],
'min_samples_split': [, , ]
}
grid_search = GridSearchCV(model, param_grid, cv=, scoring='accuracy')
grid_search.fit(X_train, y_train)
best_model = grid_search.best_estimator_
pickle
或 joblib
库。比如用 joblib
保存模型:import joblib
joblib.dump(best_model, 'best_model.pkl')
loaded_model = joblib.load('best_model.pkl')
predictions = loaded_model.predict(X_test)
from sklearn.datasets import load_iris
data = load_iris()
X = data.data
y = data.target
feature_names = data.feature_names
target_names = data.target_names
X.shape
显示有 150 个样本,4 个特征,y.shape
显示有 150 个标签。接着做一些基本的探索性分析,比如用 Plotly 画一个三维散点图,看看不同类别鸢尾花的特征分布:import plotly.graph_objects as go
fig = go.Figure(data=[go.Scatter3d(
x=X[:, ],
y=X[:, ],
z=X[:, ],
mode='markers',
marker=dict(
color=y,
size=,
colorscale='Viridis',
line=dict(width=)
),
text=target_names[y]
)])
fig.update_layout(scene=dict(xaxis_title=feature_names[], yaxis_title=feature_names[], zaxis_title=feature_names[]), title="鸢尾花数据集三维散点图")
fig.show()
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
from sklearn.svm import SVC
model = SVC(kernel='linear', random_state=)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, y_pred)
print(f"准确率:{accuracy:.4f}")
C
和 gamma
参数:param_grid = {'C': [0.1, , , ], 'gamma': [, 0.1, 0.01, 0.001], 'kernel': ['rbf', 'linear']}
grid_search = GridSearchCV(SVC(), param_grid, refit=True, verbose=, cv=)
grid_search.fit(X_train, y_train)
best_svm_model = grid_search.best_estimator_
y_pred_best = best_svm_model.predict(X_test)
accuracy_best = accuracy_score(y_test, y_pred_best)
print(f"调优后准确率:{accuracy_best:.4f}")
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
X_set, y_set = X_scaled[:, :], y
X1, X2 = np.meshgrid(np.arange(start=X_set[:, ].min() - , stop=X_set[:, ].max() + , step=0.01),
np.arange(start=X_set[:, ].min() - , stop=X_set[:, ].max() + , step=0.01))
plt.contourf(X1, X2, best_svm_model.predict(np.c_[X1.ravel(), X2.ravel()]).reshape(X1.shape),
alpha=0.75, cmap=ListedColormap(('red', 'green', 'blue'))分享到:
1000 粉丝的公众号,在很多人眼里可能还只是个 “小透明”。但你知道吗?这个阶段恰恰是搭建知识付费产品的黄金起点。不用羡慕那些动辄几万粉丝的大号,他们的变现模式未必适合你。今天就拆解一套实操方案,哪
公众号文章仿写工具怎么用?保姆级图文教程来了 一、工具选择:适合你的才是最好的 在开始使用公众号文章仿写工具之前,得先根据自己的需求选对工具。市面上的工具五花八门,功能和适用场景都不一样。比如新手可能
? 学科网 K12 资源大揭秘:多版本教材全覆盖,全学科资源任你选! 家人们,今天咱们来好好唠唠学科网的 K12 资源。作为一个深耕教育领域多年的平台,学科网在资源覆盖和适用性上到底表现如何?尤其是大
? 自研大模型筑基,打造企业级 AI 数字员工新标杆 在企业数字化转型的浪潮中,司马阅推出的 2025 最新方案 —— 司马诸葛 AI 数字员工平台,凭借其独特的技术架构和场景化解决方案,正在重新定义
? 阿里图标库对比传统工具优势在哪?2025 最新版海量矢量图标助力项目视觉品质提升! 在互联网项目开发和设计领域,图标资源的选择直接影响着项目的视觉品质和开发效率。传统工具如 Adobe Illus
✨HumanFest 核心玩法全解析:从入门到深度参与的实战指南 ✨一、快速了解 HumanFest:一场颠覆认知的智能交互实验 HumanFest 本质上是一个聚焦「人机对话真实性测试」的沉浸式活动
? 掌握这招,轻松玩转 Voicify.AI 2025:多语言合成 + 自定义模型训练全攻略 在如今这个信息爆炸的时代,语音内容的需求越来越大,不管是做短视频、搞直播,还是做教育、搞跨境电商,都离不开
? 2025 最新工具:TWMate 支持 Windows/Mac,批量下载 Twitter 视频攻略 在社交媒体内容创作领域,快速高效地获取素材是提升生产力的关键。今天给大家带来一款神器 ——TWM