当前位置:   article > 正文

机器学习从入门到精通:Jupyter Notebook实战指南_notebook建模

notebook建模

        机器学习作为人工智能领域的核心组成,是计算机程序学习数据经验以优化自身算法、并产生相应的“智能化的“建议与决策的过程。随着大数据和 AI 的发展,越来越多的场景需要 AI 手段解决现实世界中的真实问题,并产生我们所需要的价值。

        机器学习的建模流程包括明确业务问题、收集及输入数据、模型训练、模型评估、模型决策一系列过程。对于机器学习工程师而言,他们更擅长的是算法、模型、数据探索的工作,而对于工程化的能力则并不是其擅长的工作。除此之外,机器学习过程中还普遍着存在的 IDE 本地维护成本高、工程部署复杂、无法线上协同等问题,导致建模成本高且效率低下。

Jupyter 读取文件

  1. import subprocess
  2. import pandas as pd
  3. res_list = subprocess.Popen(['ls', '/datasource/testErfenlei'],
  4. shell=False,
  5. stdout=subprocess.PIPE,
  6. stderr=subprocess.PIPE).communicate()
  7. for res in res_list:
  8. print(res.decode())
  9. filenames = res.decode().split() # 将输出结果按空格分割成文件名列表
  10. for filename in filenames:
  11. if filename == 'erfenl.csv': # 根据实际文件名来判断
  12. csv_data = pd.read_csv('/datasource/testErfenlei/' + filename) # 读取CSV文件
  13. print(csv_data)

Jupyter Notebook建模-双曲线图

  1. # 导入所需的库
  2. import numpy as np
  3. import pandas as pd
  4. import matplotlib.pyplot as plt
  5. # 创建一个数组
  6. x = np.linspace(0, 10, num=100)
  7. # 计算正弦和余弦值
  8. sin_values = np.sin(x)
  9. cos_values = np.cos(x)
  10. # 将数据存储在 Pandas 数据帧中
  11. df = pd.DataFrame({'x': x, 'sin': sin_values, 'cos': cos_values})
  12. # 绘制正弦和余弦曲线
  13. plt.plot('x', 'sin', data=df, label='sin(x)')
  14. plt.plot('x', 'cos', data=df, label='cos(x)')
  15. # 添加图例和标题
  16. plt.legend()
  17. plt.title('Sine and Cosine Curves')
  18. # 显示图形
  19. plt.show()

Jupyter Notebook

生成PMML文件1
  1. from sklearn.datasets import load_iris
  2. from sklearn.tree import DecisionTreeClassifier
  3. from sklearn2pmml import PMMLPipeline, sklearn2pmml
  4. # 加载iris数据集
  5. iris = load_iris()
  6. # 训练决策树模型
  7. dt = DecisionTreeClassifier()
  8. dt.fit(iris.data, iris.target)
  9. # 创建PMMLPipeline对象
  10. pmml_pipeline = PMMLPipeline([
  11. ("classifier", dt)
  12. ])
  13. # 导出模型为PMML文件
  14. sklearn2pmml(pmml_pipeline, "iris_decision_tree.pmml")
 生成PMML文件2
  1. from sklearn.datasets import load_boston
  2. from sklearn.linear_model import LinearRegression
  3. from sklearn2pmml import PMMLPipeline, sklearn2pmml
  4. # 加载波士顿房价数据集
  5. boston = load_boston()
  6. # 构建线性回归模型
  7. lr = LinearRegression()
  8. # 使用 PMMLPipeline 包装模型
  9. pipeline = PMMLPipeline([("lr", lr)])
  10. # 使用数据拟合模型
  11. pipeline.fit(boston.data, boston.target)
  12. # 将模型保存为 PMML 文件
  13. sklearn2pmml(pipeline, "linear_regression.pmml")

R Notebook建模 - 散点图

  1. # 导入所需的库
  2. library(ggplot2)
  3. # 创建一个数据框
  4. df <- data.frame(
  5. x = 1:10,
  6. y = c(3, 5, 6, 8, 9, 10, 11, 13, 14, 15)
  7. )
  8. # 绘制散点图
  9. ggplot(df, aes(x, y)) +
  10. geom_point() +
  11. labs(title="Scatter Plot of X and Y", x="X", y="Y")

R Notebook获取训练数据集

  1. setwd(dir=”/datasource”)
  2. dir()

PySpark Notebook建模

  1. # 导入所需库
  2. from pyspark.sql import SparkSession
  3. from pyspark.ml.feature import VectorAssembler
  4. from pyspark.ml.regression import LinearRegression
  5. from pyspark.ml.evaluation import RegressionEvaluator
  6. # 创建 SparkSession
  7. spark = SparkSession.builder.appName("LinearRegression").getOrCreate()
  8. # 创建 DataFrame
  9. data = [(1.2, 3.4, 5.6), (2.3, 4.5, 6.7), (3.4, 5.6, 7.8), (4.5, 6.7, 8.9)]
  10. columns = ["feature1", "feature2", "label"]
  11. df = spark.createDataFrame(data, columns)
  12. # 将特征列组合到向量中
  13. assembler = VectorAssembler(inputCols=["feature1", "feature2"], outputCol="features")
  14. df = assembler.transform(df)
  15. # 拆分数据集为训练集和测试集
  16. train_df, test_df = df.randomSplit([0.7, 0.3], seed=42)
  17. # 创建线性回归模型并拟合训练集
  18. lr = LinearRegression(featuresCol="features", labelCol="label")
  19. model = lr.fit(train_df)
  20. # 在测试集上进行预测并计算其平均误差
  21. predictions = model.transform(test_df)
  22. # mse = predictions.agg({"prediction": "mean_squared_error"}).collect()[0][0]
  23. # mse = predictions.agg(mean_squared_error(predictions["label"], predictions["prediction"])).collect()[0][0]
  24. evaluator = RegressionEvaluator(predictionCol="prediction", labelCol="label", metricName="mse")
  25. mse = evaluator.evaluate(predictions)
  26. # 显示结果
  27. print(f"Mean Squared Error on Test Set: {mse}")
  28. # 停止 SparkSession
  29. spark.stop()

PySpark Notebook建模 -折线图

  1. # 导入所需库和模块
  2. import matplotlib.pyplot as plt
  3. from pyspark.sql.functions import col
  4. from pyspark.sql import SparkSession
  5. # 创建 SparkSession
  6. spark = SparkSession.builder.appName("LinePlot").getOrCreate()
  7. # 创建 DataFrame
  8. data = [(1, 2), (2, 4), (3, 7), (4, 8), (5, 9)]
  9. columns = ["x", "y"]
  10. df = spark.createDataFrame(data, columns)
  11. # 提取 x 和 y 列并将其转换为 Pandas 数据框
  12. pandas_df = df.select("x", "y").orderBy("x").toPandas()
  13. # 绘制折线图
  14. plt.plot(pandas_df["x"], pandas_df["y"])
  15. # 添加标题和轴标签
  16. plt.title("Line Plot")
  17. plt.xlabel("X")
  18. plt.ylabel("Y")
  19. # 显示图形
  20. plt.show()
  21. # 停止 SparkSession
  22. spark.stop()

C语言Notebook 建模

  1. #include <stdio.h>
  2. int main() {
  3. int arr[] = {3, 7, 1, 9, 5};
  4. int size = sizeof(arr) / sizeof(arr[0]);
  5. // 找到最大值,以便缩放柱状图
  6. int max_value = arr[0];
  7. for (int i = 1; i < size; i++) {
  8. if (arr[i] > max_value) {
  9. max_value = arr[i];
  10. }
  11. }
  12. // 打印柱状图
  13. printf("Bar chart:\n");
  14. for (int i = max_value; i > 0; i--) {
  15. for (int j = 0; j < size; j++) {
  16. if (arr[j] >= i) {
  17. printf("* ");
  18. } else {
  19. printf(" ");
  20. }
  21. }
  22. printf("\n");
  23. }
  24. // 打印横轴标签
  25. for (int i = 0; i < size; i++) {
  26. printf("%d ", arr[i]);
  27. }
  28. printf("\n");
  29. return 0;
  30. }

C++Notebook 建模

  1. #include <iostream>
  2. using namespace std;
  1. int f1()
  2. {
  3. std::cout <<"hello world1\n";
  4. return 1;
  5. }
  6. int a = 110;
  7. cout << f1() << endl;
  8. cout <<1010<<endl;

使用pytorch

  1. import torch
  2. import torch.nn as nn
  3. import torch.optim as optim
  4. # 定义一个简单的神经网络模型
  5. class SimpleNet(nn.Module):
  6. def __init__(self, input_size, hidden_size, output_size):
  7. super(SimpleNet, self).__init__()
  8. self.fc1 = nn.Linear(input_size, hidden_size)
  9. self.relu = nn.ReLU()
  10. self.fc2 = nn.Linear(hidden_size, output_size)
  11. def forward(self, x):
  12. out = self.fc1(x)
  13. out = self.relu(out)
  14. out = self.fc2(out)
  15. return out
  16. # 准备数据
  17. input_size = 10
  18. hidden_size = 20
  19. output_size = 5
  20. batch_size = 32
  21. input_data = torch.randn(batch_size, input_size)
  22. target_data = torch.randn(batch_size, output_size)
  23. # 实例化模型
  24. model = SimpleNet(input_size, hidden_size, output_size)
  25. # 定义损失函数和优化器
  26. criterion = nn.MSELoss()
  27. optimizer = optim.SGD(model.parameters(), lr=0.1)
  28. # 训练模型
  29. num_epochs = 100
  30. for epoch in range(num_epochs):
  31. # 前向传播
  32. output = model(input_data)
  33. loss = criterion(output, target_data)
  34. # 反向传播和优化
  35. optimizer.zero_grad()
  36. loss.backward()
  37. optimizer.step()
  38. # 打印训练信息
  39. if (epoch+1) % 10 == 0:
  40. print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))

使用TensorFlow

  1. import tensorflow as tf
  2. # 检查是否有可用的GPU设备
  3. if tf.test.is_gpu_available():
  4. print('GPU 设备可用')
  5. else:
  6. print('GPU 设备不可用')
  7. # 创建一个简单的神经网络模型
  8. model = tf.keras.models.Sequential([
  9. tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)),
  10. tf.keras.layers.Dense(64, activation='relu'),
  11. tf.keras.layers.Dense(10, activation='softmax')
  12. ])
  13. # 准备数据
  14. (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
  15. # 数据预处理
  16. x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
  17. x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
  18. y_train = tf.keras.utils.to_categorical(y_train, num_classes=10)
  19. y_test = tf.keras.utils.to_categorical(y_test, num_classes=10)
  20. # 编译模型
  21. model.compile(optimizer='adam',
  22. loss='categorical_crossentropy',
  23. metrics=['accuracy'])
  24. # 在GPU上训练模型
  25. with tf.device('/GPU:0'):
  26. model.fit(x_train, y_train, batch_size=128, epochs=10, validation_split=0.2)
  27. # 在GPU上评估模型
  28. with tf.device('/GPU:0'):
  29. test_loss, test_acc = model.evaluate(x_test, y_test)
  30. print('Test accuracy:', test_acc)

二分类-模型评估脚本

描述:根据花萼长度、花萼宽度、花瓣长度、花瓣宽度四个特征,将鸢尾花分为两个类别
  1. # 加载数据集
  2. iris = load_iris()
  3. X, y = iris.data[:, :2], iris.target
  4. # 划分训练集和测试集
  5. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  6. # 创建决策树分类器模型
  7. clf = DecisionTreeClassifier()
  8. # 在训练集上拟合模型
  9. clf.fit(X_train, y_train)
  10. # 在测试集上进行预测并计算准确率
  11. y_pred = clf.predict(X_test)
  12. accuracy = accuracy_score(y_test, y_pred)
  13. # 绘制二分类x轴和y轴图像
  14. plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')
  15. plt.xlabel('Sepal length')
  16. plt.ylabel('Sepal width')
  17. plt.show()

回归-模型评估脚本

描述:使用该镇的人均犯罪率、一氧化碳浓度、低收入人群占比等13个属性,来预测房屋的价格

  1. # 波士顿房价预测回归类型
  2. # 导入所需的库
  3. from sklearn.datasets import load_boston
  4. from sklearn.model_selection import train_test_split
  5. from sklearn.linear_model import LinearRegression
  6. from sklearn.metrics import r2_score
  7. import matplotlib.pyplot as plt
  8. # 加载数据集
  9. boston = load_boston()
  10. X, y = boston.data[:, 0], boston.target
  11. # 划分训练集和测试集
  12. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  13. # 创建线性回归模型
  14. model = LinearRegression()
  15. # 在训练集上拟合模型
  16. model.fit(X_train.reshape(-1, 1), y_train)
  17. # 在测试集上进行预测并计算R^2值
  18. y_pred = model.predict(X_test.reshape(-1, 1))
  19. r2_score = r2_score(y_test, y_pred)
  20. # 绘制回归类型x轴和y轴图像
  21. plt.scatter(X, y)
  22. plt.plot(X_test, y_pred, color='red', linewidth=3)
  23. plt.xlabel('Average number of rooms per dwelling')
  24. plt.ylabel('Median value of owner-occupied homes in $1000s')
  25. plt.show()

聚类-模型评估脚本

描述:根据花萼长度、花萼宽度、花瓣长度、花瓣宽度四个特征,对鸢尾花进行聚类
  1. # 鸢尾花聚类
  2. # 导入所需的库
  3. from sklearn.datasets import load_iris
  4. from sklearn.cluster import KMeans
  5. import matplotlib.pyplot as plt
  6. # 加载数据集
  7. iris = load_iris()
  8. X, y = iris.data, iris.target
  9. # 创建KMeans模型并拟合数据
  10. kmeans = KMeans(n_clusters=3, random_state=42)
  11. kmeans.fit(X)
  12. # 绘制聚类图表
  13. fig, ax = plt.subplots(figsize=(8, 6))
  14. plt.scatter(X[kmeans.labels_ == 0, 0], X[kmeans.labels_ == 0, 1], s = 100, c = 'red', label = 'Cluster 1')
  15. plt.scatter(X[kmeans.labels_ == 1, 0], X[kmeans.labels_ == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')
  16. plt.scatter(X[kmeans.labels_ == 2, 0], X[kmeans.labels_ == 2, 1], s = 100, c = 'green', label = 'Cluster 3')
  17. # 绘制聚类中心点
  18. plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s = 200, marker='.', c = 'black', label = 'Centroids')
  19. plt.legend()
  20. plt.xlabel('Sepal length')
  21. plt.ylabel('Sepal width')
  22. plt.show()

统计分析脚本

描述:使用泰坦尼克号数据集进行基本的数据分析
  1. # 数据分析
  2. # 导入必要的库
  3. import seaborn as sns
  4. import matplotlib.pyplot as plt
  5. # 从 Seaborn 库中加载泰坦尼克号数据集,存储为 DataFrame
  6. titanic_data = sns.load_dataset('titanic')
  7. # 数据基本情况概览
  8. print("========== Data Overview ==========")
  9. print(titanic_data.head())
  10. print("\n")
  11. # 数据统计信息
  12. print("========== Data Statistics ==========")
  13. print(titanic_data.describe())
  14. print("\n")
  15. # 缺失值数量统计
  16. print("========== Missing Value Count ==========")
  17. print(titanic_data.isnull().sum())
  18. print("\n")
  19. # 幸存者数量统计
  20. print("========== Survival Count ==========")
  21. print(titanic_data['survived'].value_counts())
  22. print("\n")
  23. # 不同年龄段的存活率比较可视化
  24. age_bins = [0, 10, 20, 30, 40, 50, 60, 70, 80]
  25. age_labels = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80']
  26. titanic_data['age_group'] = pd.cut(titanic_data['age'], bins=age_bins, labels=age_labels)
  27. sns.barplot(x='age_group', y='survived', data=titanic_data)
  28. plt.title('Survival Rate by Age Group')
  29. plt.show()

深度学习-多分类-模型评估脚本

描述:利用DNN模型对鸢尾花数据集进行分类
  1. # 鸢尾花多分类
  2. # 导入必要的库
  3. import pandas as pd
  4. import numpy as np
  5. import matplotlib.pyplot as plt
  6. from sklearn.model_selection import train_test_split
  7. from sklearn.preprocessing import StandardScaler
  8. import tensorflow as tf
  9. from tensorflow.keras.utils import to_categorical
  10. # 加载鸢尾花数据集
  11. iris_data = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None)
  12. X = iris_data.iloc[:, :4].values
  13. y = iris_data.iloc[:, 4].values
  14. # 将类别标签转成数字标签
  15. label_dict = {k: i for i, k in enumerate(np.unique(y))}
  16. y = np.array([label_dict[label] for label in y])
  17. # 数据标准化处理
  18. scaler = StandardScaler()
  19. X = scaler.fit_transform(X)
  20. # 将标签进行one-hot编码
  21. y = to_categorical(y)
  22. # 分割训练集和测试集
  23. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  24. # 定义DNN模型
  25. model = tf.keras.models.Sequential([
  26. tf.keras.layers.Dense(units=16, activation='relu', input_shape=(4,),
  27. kernel_regularizer=tf.keras.regularizers.L2(0.01)),
  28. tf.keras.layers.Dropout(rate=0.3),
  29. tf.keras.layers.Dense(units=3, activation='softmax')
  30. ])
  31. model.summary()
  32. # 编译并训练模型
  33. model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
  34. history = model.fit(X_train, y_train, epochs=50, batch_size=16, validation_data=(X_test, y_test))
  35. # 展示模型的训练曲线
  36. plt.plot(history.history['accuracy'], label='training accuracy')
  37. plt.plot(history.history['val_accuracy'], label='validation accuracy')
  38. plt.title('Model Accuracy')
  39. plt.xlabel('Epoch')
  40. plt.ylabel('Accuracy')
  41. plt.legend()
  42. plt.show()
  43. # 在测试集上进行分类预测
  44. y_pred = np.argmax(model.predict(X_test), axis=-1)
  45. # 可视化分类结果与实际结果比较
  46. plt.scatter(X_test[:, 0], X_test[:, 2], c=y_pred, cmap='coolwarm')
  47. plt.title('Predicted Labels')
  48. plt.xlabel('Sepal Length (cm)')
  49. plt.ylabel('Petal Length (cm)')
  50. plt.show()
  51. plt.scatter(X_test[:, 0], X_test[:, 2], c=np.argmax(y_test, axis=-1), cmap='coolwarm')
  52. plt.title('Actual Labels')
  53. plt.xlabel('Sepal Length (cm)')
  54. plt.ylabel('Petal Length (cm)')
  55. plt.show()

        当我们在网上搜索相关的 Notebook 代码文件时,搜索的结果比较零散。为了帮助大家更好地整理和使用这些基础代码,特别整理了一些示例,希望对大家有所帮助!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/711243
推荐阅读
相关标签
  

闽ICP备14008679号