Контролируемое машинное обучение:
Тип обучения, при котором ввод и вывод уже передаются конкретной модели, и при этом модель проходит обучение и дает прогнозируемые значения, которые по сравнению с выходными значениями дают наилучшую линию соответствия.
Линейная регрессия:
Само название предполагает, что оно дает линейную зависимость между зависимой и независимой переменной, где уравнение:
y= mx +c, где m — наклон, а c — точка пересечения.
Почему я выбрал линейную регрессию для этого набора данных?
Прогнозирование значений цены закрытия набора данных на основе переменных характеристик, таких как открытие, максимум, минимум и объем, дает наилучшую линию или линейную связь между прогнозируемым значением (Y) и фактическим значением.
Использование метода регрессии, т. Е. Линейной регрессии, дает точные значения для прогнозируемого, что говорит о том, что модель хорошо обучена на наборе данных и имеет большой процент точности.
Шаг 1. Импортируйте все необходимые библиотеки в набор данных.
#Linear regression is the relationship between dependent and independent variable(feature/predictive variable) import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline tesla_file_path= (r'C:\Users\ansht\Downloads\TSLA.csv') tesla_df= pd.read_csv(tesla_file_path)
Шаг 2. Получите статическую информацию о наборе данных
Шаг 3. Проверьте, присутствуют ли нулевые значения, и, если они есть, суммируйте их.
# to check if any null values are there or not in the dataset tesla_df.isnull() #gives false means no null values in the dataset and so their sum is also 0 # to calculate the sum of null values. As sum is 0 it will return all the values as 0 tesla_df.isnull().sum() #to display the null values dropna() method is used tesla_df.dropna(axis=0,how='any', thresh=None, subset=None,inplace=False) #as no null values are obtained so will display all
Шаг 4. Разделите данные на две части: 1. Обучение 2. Тестирование.
from sklearn import the libraries from sklearn.model_selection import train_test_split x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3) #training data into 70% and testing as 30% #Creating an x array as we'll use it for the prediction of y x=tesla_df[['Open','High','Volume','Low']] #Creating an array y for the value of which we want to predict y=tesla_df['Close']
Шаг 5. Создание и настройка модели
from sklearn.linear_model import LinearRegression #creating a linear regressor model model=LinearRegression() #as a overfit model doesn't perform well on the training data and rather on the validation part tesla_df=model.fit(x_train,y_train) print(model.coef_) #printing model's coefficients and intercepts print(model.intercept_)
Шаг 6. Предскажите значения и сравните их с фактическими значениями.
#predict only takes parameter x and gives automatically the values of y. Compare y with the predictions parameter to get the accuracy prediction=model.predict(x_test) comparison = pd.DataFrame({'Predicted Values':prediction,'Actual Values':y_test}) print (comparison.head(10))
Шаг 7. Найдите функцию затрат или функцию потерь с помощью среднеквадратичной ошибки
#mean absolute error is actually actual value-predicted value divided by n number of observations from sklearn import metrics metrics.mean_absolute_error(y_test, prediction) #Note:RMSE will always be greater or equal to the MAE value. MSE(RMSE=sqrt(Mean Square Error)) #No inbuilt method to find the RMSE in sciikit model metrics.mean_squared_error(y_test, prediction) #Calculating RMSE np.sqrt(metrics.mean_squared_error(y_test, prediction))
Шаг 8. Визуализируйте данные с помощью методов визуализации данных
#Scatterplot shows relation between two continous variables so x and y plt.scatter(y_test,prediction,color='red') #A perfectly straight diagonal line in this scatterplot would indicate that our model perfectly predicted the y-array values. plt.hist(y_test-prediction) sns.regplot(y_test,prediction)