Advertisement
gagarin_1982

проект по спарку

Aug 27th, 2024
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.93 KB | None | 0 0
  1. # загрузка библиотек
  2. import pandas as pd
  3. import numpy as np
  4.  
  5. import pyspark
  6. from pyspark.sql import SparkSession
  7. from pyspark.sql.types import *
  8. import pyspark.sql.functions as F
  9.  
  10. from pyspark.ml.feature import StringIndexer, VectorAssembler, StandardScaler
  11. from pyspark.ml.classification import LogisticRegression
  12.  
  13.  
  14. pyspark_version = pyspark.__version__
  15. if int(pyspark_version[:1]) == 3:
  16. from pyspark.ml.feature import OneHotEncoder
  17. elif int(pyspark_version[:1]) == 2:
  18. from pyspark.ml.feature import OneHotEncodeEstimator
  19.  
  20. RANDOM_SEED = 2022
  21.  
  22. # инициируем сессию спарк
  23. spark = SparkSession.builder \
  24. .master("local") \
  25. .appName("Housing - Linreg") \
  26. .getOrCreate()
  27.  
  28. # загружаем данные
  29. df = spark.read.option('header', 'true').csv('/datasets/housing.csv', inferSchema = True)
  30.  
  31. # проверяем названия полей
  32. df.columns
  33.  
  34. # считаем количество записей
  35. df.count()
  36.  
  37. # удаляем записи с пропущенными значениями
  38. subset = ['longitude',
  39. 'latitude',
  40. 'housing_median_age',
  41. 'total_rooms',
  42. 'total_bedrooms',
  43. 'population',
  44. 'households',
  45. 'median_income',
  46. 'median_house_value',
  47. 'ocean_proximity']
  48.  
  49. df = df.na.drop(subset=subset)
  50.  
  51. # считаем количество записей после удаления
  52. df.count()
  53.  
  54. # размечаем поля с таргетом, входящими категориальными, входящими числовыми
  55. categorical_cols = ['ocean_proximity']
  56.  
  57. numerical_cols = [
  58. 'longitude',
  59. 'latitude',
  60. 'housing_median_age',
  61. 'total_rooms',
  62. 'total_bedrooms',
  63. 'population',
  64. 'households',
  65. 'median_income',
  66. ]
  67.  
  68. target = 'median_house_value'
  69.  
  70. # трансформация категориальных входящих признаков
  71. indexer = StringIndexer(inputCols=categorical_cols,
  72. outputCols=[c+'_idx' for c in categorical_cols])
  73. df = indexer.fit(df).transform(df)
  74.  
  75. cols = [c for c in df.columns for i in categorical_cols if (c.startswith(i))]
  76. df.select(cols).show(3)
  77.  
  78.  
  79. encoder = OneHotEncoder(inputCols=[c+'_idx' for c in categorical_cols],
  80. outputCols=[c+'_ohe' for c in categorical_cols])
  81. df = encoder.fit(df).transform(df)
  82.  
  83. cols = [c for c in df.columns for i in categorical_cols if (c.startswith(i))]
  84. df.select(cols).show(3)
  85.  
  86.  
  87. categorical_assembler = VectorAssembler(inputCols=[c+'_ohe' for c in categorical_cols], outputCol="categorical_features")
  88. df = categorical_assembler.transform(df)
  89.  
  90. # трансформация числовых входящих признаков
  91. numerical_assembler = VectorAssembler(inputCols=numerical_cols, outputCol="numerical_features")
  92. df = numerical_assembler.transform(df)
  93.  
  94. standardScaler = StandardScaler(inputCol='numerical_features', outputCol="numerical_features_scaled")
  95. df = standardScaler.fit(df).transform(df)
  96.  
  97. df.columns
  98.  
  99. # соединяем все признаки в векторном представлении
  100. all_features = ['categorical_features','numerical_features_scaled']
  101. final_assembler = VectorAssembler(inputCols=all_features, outputCol="features")
  102. df = final_assembler.transform(df)
  103. df.select(all_features).show(3)
  104.  
  105. # разделяем на обучающую и тестовую выборки
  106. train_data, test_data = df.randomSplit([.8,.2], seed=RANDOM_SEED)
  107. print(train_data.count(), test_data.count())
  108.  
  109. # обучаем модель
  110. lr = LogisticRegression(labelCol=target, featuresCol='features')
  111. model = lr.fit(train_data)
  112.  
  113. # на последнем шаге блокнот уходит на вычисления и уже не возвращается (на блоке отображается звездочка, можно ждать хоть час - изменений нет, хотя это линейная модель.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement