import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import datetime
# Load the Tesla Dataset
tesla_stock = pd.read_csv('C:/Users/Admin/Downloads/AI/Tesla.csv')
# Dynamically handle missing or renamed 'Close' column
possible_target_columns = ['Close', 'Last', 'Price', 'Adjusted Close', 'VWAP',
'Close/Last']
target_column = None
# Print available columns for debugging
print("Columns available in the dataset:", tesla_stock.columns)
for col in possible_target_columns:
if col in tesla_stock.columns:
target_column = col
print(f"Using '{col}' as the target column for predictions.")
break
# Handle case when no suitable column is found
if target_column is None:
print("No suitable column for predictions found. Please check the dataset.")
raise KeyError("Ensure the dataset includes a column with stock prices (e.g., 'Close',
'Close/Last').")
# Clean the numeric columns (removing '$' and converting to float)
for column in ['Open', 'High', 'Low', 'Close/Last', 'Volume']:
if column in tesla_stock.columns:
tesla_stock[column] = tesla_stock[column].replace('[\$,]', '',
regex=True).astype(float)
# Convert 'Date' to datetime and set as index
tesla_stock['Date'] = pd.to_datetime(tesla_stock['Date'])
tesla_stock.set_index('Date', inplace=True)
# Define features and target variable
features = ['Open', 'High', 'Low', 'Volume']
X = tesla_stock[features]
y = tesla_stock[target_column]
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Train the Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)
# Make predictions
predicted = model.predict(X_test)
# Evaluate the model
print("Model Score (R²):", model.score(X_test, y_test))
print("Mean Absolute Error:", metrics.mean_absolute_error(y_test, predicted))
print("Mean Squared Error:", metrics.mean_squared_error(y_test, predicted))
print("Root Mean Squared Error:", math.sqrt(metrics.mean_squared_error(y_test,
predicted)))
# Plot Actual vs Predicted Prices for the test set
dfr = pd.DataFrame({'Actual': y_test, 'Predicted': predicted})
plt.figure(figsize=(14, 8))
dfr.head(25).plot(kind='bar', figsize=(14, 8))
plt.title("Actual vs Predicted Prices")
plt.xlabel("Sample")
plt.ylabel("Price (USD)")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
plt.show()
# Predict the next 30 days
last_date = tesla_stock.index[-1] # Last date in historical data
last_price = tesla_stock[target_column].iloc[-1] # Last price in historical data
future_dates = [last_date + datetime.timedelta(days=i) for i in range(1, 31)] #
Generate next 30 days
# Create a placeholder DataFrame for future features
future_features = pd.DataFrame(index=future_dates)
for feature in features:
if feature in tesla_stock.columns:
future_features[feature] = tesla_stock[feature].mean() # Use the mean value of
each feature
# Predict future prices using the trained model
future_predictions = model.predict(future_features)
# Combine the historical and future data for a seamless plot
all_dates = list(tesla_stock.index) + list(future_dates) # Combine historical and
future dates
all_prices = list(tesla_stock[target_column]) + list(future_predictions) # Combine
historical and predicted prices
# Plot historical data and future predictions
plt.figure(figsize=(14, 8))
plt.plot(tesla_stock.index, tesla_stock[target_column], label='Historical Prices',
color='blue')
plt.plot(future_dates, future_predictions, label='30-Day Future Predictions',
color='red')
plt.title('Tesla Stock Price Prediction for the Next 30 Days')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.xticks(rotation=45)
plt.show()
# Display future predictions
future_features['Predicted_Close'] = future_predictions
print(future_features[['Predicted_Close']])
введите здесь описание изображения
я пытаюсь, чтобы красная линия соединялась с концом графика и как бы изгибалась вниз до того места, где она находится. Вместо случайной короткой красной линии в начале, потому что это кажется немного беспорядочным. Я пытался это сделать, но у меня действительно были проблемы с этим. был бы очень признателен, если бы кто-нибудь мог мне помочь с этим, спасибо.
[code]import math import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import datetime
# Load the Tesla Dataset tesla_stock = pd.read_csv('C:/Users/Admin/Downloads/AI/Tesla.csv')
# Print available columns for debugging print("Columns available in the dataset:", tesla_stock.columns)
for col in possible_target_columns: if col in tesla_stock.columns: target_column = col print(f"Using '{col}' as the target column for predictions.") break
# Handle case when no suitable column is found if target_column is None: print("No suitable column for predictions found. Please check the dataset.") raise KeyError("Ensure the dataset includes a column with stock prices (e.g., 'Close', 'Close/Last').")
# Clean the numeric columns (removing '$' and converting to float) for column in ['Open', 'High', 'Low', 'Close/Last', 'Volume']: if column in tesla_stock.columns: tesla_stock[column] = tesla_stock[column].replace('[\$,]', '', regex=True).astype(float)
# Convert 'Date' to datetime and set as index tesla_stock['Date'] = pd.to_datetime(tesla_stock['Date']) tesla_stock.set_index('Date', inplace=True)
# Define features and target variable features = ['Open', 'High', 'Low', 'Volume'] X = tesla_stock[features] y = tesla_stock[target_column]
# Split data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
# Train the Linear Regression model model = LinearRegression() model.fit(X_train, y_train)
# Make predictions predicted = model.predict(X_test)
# Evaluate the model print("Model Score (R²):", model.score(X_test, y_test)) print("Mean Absolute Error:", metrics.mean_absolute_error(y_test, predicted)) print("Mean Squared Error:", metrics.mean_squared_error(y_test, predicted)) print("Root Mean Squared Error:", math.sqrt(metrics.mean_squared_error(y_test, predicted)))
# Plot Actual vs Predicted Prices for the test set dfr = pd.DataFrame({'Actual': y_test, 'Predicted': predicted}) plt.figure(figsize=(14, 8)) dfr.head(25).plot(kind='bar', figsize=(14, 8)) plt.title("Actual vs Predicted Prices") plt.xlabel("Sample") plt.ylabel("Price (USD)") plt.xticks(rotation=45, ha="right") plt.tight_layout() plt.show()
# Predict the next 30 days last_date = tesla_stock.index[-1] # Last date in historical data last_price = tesla_stock[target_column].iloc[-1] # Last price in historical data future_dates = [last_date + datetime.timedelta(days=i) for i in range(1, 31)] # Generate next 30 days
# Create a placeholder DataFrame for future features future_features = pd.DataFrame(index=future_dates) for feature in features: if feature in tesla_stock.columns: future_features[feature] = tesla_stock[feature].mean() # Use the mean value of each feature
# Predict future prices using the trained model future_predictions = model.predict(future_features)
# Combine the historical and future data for a seamless plot all_dates = list(tesla_stock.index) + list(future_dates) # Combine historical and future dates all_prices = list(tesla_stock[target_column]) + list(future_predictions) # Combine historical and predicted prices
# Plot historical data and future predictions plt.figure(figsize=(14, 8)) plt.plot(tesla_stock.index, tesla_stock[target_column], label='Historical Prices', color='blue') plt.plot(future_dates, future_predictions, label='30-Day Future Predictions', color='red') plt.title('Tesla Stock Price Prediction for the Next 30 Days') plt.xlabel('Date') plt.ylabel('Price (USD)') plt.legend() plt.xticks(rotation=45) plt.show()
# Display future predictions future_features['Predicted_Close'] = future_predictions print(future_features[['Predicted_Close']]) [/code] введите здесь описание изображения я пытаюсь, чтобы красная линия соединялась с концом графика и как бы изгибалась вниз до того места, где она находится. Вместо случайной короткой красной линии в начале, потому что это кажется немного беспорядочным. Я пытался это сделать, но у меня действительно были проблемы с этим. был бы очень признателен, если бы кто-нибудь мог мне помочь с этим, спасибо.
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import datetime
Я учусь на пятом семестре. Я изучал основы программирования, ООП, структуры данных и алгоритмы, операционную систему, базу данных (SQL). Я создал несколько проектов, но хочу получить отраслевой опыт, например работу над проектами, и по этой причине...
Проблема:
У меня есть CSV-файл с двумя столбцами: «Время» и «Интенсивность», который я могу построить, чтобы получить очень плотный линейный график. Время варьируется от 900 до 11 496 секунд, и на каждую секунду у меня есть 200 наблюдений.
Вместо...
Итак, я пытаюсь создать систему проката фильмов, используя ООП, и кое-что меня немного смущает. У меня есть два файла .py: один содержит только объект Movie, а другой — логику всей системы.
У меня есть метод
def movie_available(self, title):...