영화 데이터 세트 탐색 및 시각화

PHPz
풀어 주다: 2024-09-11 16:15:03
원래의
714명이 탐색했습니다.

소개

연습이 완벽을 만듭니다.

데이터 과학자라는 직업과 공통점이 많은 것. 이론은 방정식의 한 측면일 뿐입니다. 가장 중요한 측면은 이론을 실제로 적용하는 것입니다. 영화 데이터 세트를 연구하는 캡스톤 프로젝트를 개발하는 오늘의 전체 과정을 기록하도록 노력하겠습니다.

목표는 다음과 같습니다.
목표:

  1. Kaggle에서 영화 데이터세트를 다운로드하거나 TMDb API를 사용하여 검색하세요.
  2. 영화 장르, 평점, 감독 인기, 개봉 연도 동향 등 다양한 측면을 살펴보세요.
  3. 이러한 트렌드를 시각화하고 선택적으로 사용자 선호도에 따라 영화를 추천하는 대시보드를 만듭니다.

1. 데이터 수집
저는 Kaggle을 사용하여 데이터 세트를 찾기로 결정했습니다. 작업 중인 데이터 세트에 대해 원하는 중요한 변수를 염두에 두는 것이 중요합니다. 중요한 것은 내 데이터 세트에 개봉 연도 동향, 감독의 인기, 등급, 영화 장르가 포함되어야 한다는 것입니다. 결과적으로 내가 선택한 데이터세트에 최소한 다음 사항이 포함되어 있는지 확인해야 합니다.
내 데이터 세트는 Kaggle에 있었으며 아래 링크를 제공하겠습니다. 데이터 세트를 다운로드하고 압축을 풀고 추출하여 파일의 CSV 버전을 얻을 수 있습니다. 이를 통해 이미 가지고 있는 것을 이해하고 조사할 데이터에서 얻고자 하는 통찰력이 무엇인지 진정으로 깨달을 수 있습니다.

2. 데이터 설명

먼저 필수 라이브러리를 가져오고 필요한 데이터를 로드해야 합니다. 저는 코드를 더 효율적으로 작성하고 볼 수 있도록 프로젝트에 Python 프로그래밍 언어와 Jupyter Notebook을 사용하고 있습니다.
우리가 사용할 라이브러리를 가져와서 아래와 같이 데이터를 로드하게 됩니다.

Movie Dataset Exploration and Visualization

그런 다음 다음 명령을 실행하여 데이터세트에 대한 자세한 내용을 확인합니다.

data.head() # dispalys the first rows of the dataset.
data.tail() # displays the last rows of the dataset.
data.shape # Shows the total number of rows and columns.
len(data.columns)  # Shows the total number of columns.
data.columns # Describes different column names.
data.dtypes # Describes different data types.


로그인 후 복사

이제 우리는 데이터 세트가 무엇으로 구성되어 있는지, 그리고 필요한 모든 설명을 얻은 후 추출하려는 통찰력을 알고 있습니다. 예: 내 데이터세트를 사용하여 감독의 인기, 평점 분포, 영화 장르의 패턴을 조사하고 싶습니다. 또한 선호하는 감독, 장르 등 사용자가 선택한 선호도에 따라 영화를 추천하고 싶습니다.

3. 데이터 정리

이 단계에는 null 값을 찾아 제거하는 작업이 포함됩니다. 데이터 시각화를 계속 진행하기 위해 데이터 세트에서 중복 항목을 검사하고 발견된 항목을 모두 제거합니다. 이를 위해 다음 코드를 실행합니다.

1. data['show_id'].value_counts().sum() # Checks for the total number of rows in my dataset
2. data.isna().sum() # Checks for null values(I found null values in director, cast and country columns)
3. data[['director', 'cast', 'country']] = data[['director', 'cast', 'country']].replace(np.nan, "Unknown ") # Fill null values with unknown.
로그인 후 복사

그런 다음 알 수 없는 값이 있는 행을 삭제하고 해당 행이 모두 삭제되었는지 확인합니다. 또한 데이터를 정리한 남은 행 수도 확인합니다.

Movie Dataset Exploration and Visualization

다음 코드는 고유한 특성과 중복 항목을 찾습니다. 내 데이터세트에 중복된 항목이 없더라도 향후 데이터세트에 중복되는 경우를 대비해 활용해야 할 수도 있습니다.

data.duplicated().sum() # Checks for duplicates
data.nunique() # Checks for unique features
data.info # Confirms if nan values are present and also shows datatypes.
로그인 후 복사

제 날짜/시간 데이터 타입이 객체인데, 날짜/시간 형식이 맞는지 확인하고 싶어서 사용했습니다
data['date_ added']=data['date_add'].astype('datetime64[ms]')적절한 형식으로 변환하세요.

4. 데이터 시각화

  • 내 데이터 세트에는 TV 쇼와 영화라는 두 가지 유형의 변수가 있으며 막대 그래프를 사용하여 해당 변수가 나타내는 값과 함께 범주형 데이터를 표시했습니다.
    Movie Dataset Exploration and Visualization

  • 저도 위와 같은 내용을 파이차트(Pie Chart)로 표현했습니다. 사용된 코드는 다음과 같으며 예상되는 결과는 아래와 같습니다.

## Pie chart display
plt.figure(figsize=(8, 8))  
data['type'].value_counts().plot(
    kind='pie', 
    autopct='%1.1f%%',  
    colors=['skyblue', 'lightgreen'], 
    startangle=90, 
    explode=(0.05, 0) 
)
plt.title('Distribution of Content Types (Movies vs. TV Shows)')
plt.ylabel('')
plt.show()
로그인 후 복사

Movie Dataset Exploration and Visualization

  • 그런 다음 pd.crosstab(data.type, data.country)를 사용하여 출시 날짜, 국가 및 기타 요소를 기반으로 유형의 표 비교를 생성했습니다(코드에서 열을 변경해 볼 수 있음). 독립적으로). 다음은 사용할 코드와 예상되는 비교입니다. 또한 TV 쇼 제작에 앞장서는 상위 20개 국가를 확인하고 이를 막대 그래프로 시각화했습니다. 이미지의 코드를 복사하면 결과가 나와 거의 유사한지 확인할 수 있습니다.

Movie Dataset Exploration and Visualization

Movie Dataset Exploration and Visualization

  • I then checked for the top 10 movie genre as shown below. You can also use the code to check for TV shows. Just substitute with proper variable names.

Movie Dataset Exploration and Visualization

  • I extracted months and years separately from the dates provided so that I could visualize some histogram plots over the years.

Movie Dataset Exploration and Visualization

Movie Dataset Exploration and Visualization

Movie Dataset Exploration and Visualization

  • Checked for the top 10 directors with the most movies and compared them using a bar graph.

Movie Dataset Exploration and Visualization

  • Checked for the cast with the highest rating and visualized them.

Movie Dataset Exploration and Visualization

5. Recommendation System

I then built a recommendation system that takes in genre or director's name as input and produces a list of movies as per the user's preference. If the input cannot be matched by the algorithm then the user is notified.

Movie Dataset Exploration and Visualization

The code for the above is as follows:

def recommend_movies(genre=None, director=None):
    recommendations = data
    if genre:
        recommendations = recommendations[recommendations['listed_in'].str.contains(genre, case=False, na=False)]
    if director:
        recommendations = recommendations[recommendations['director'].str.contains(director, case=False, na=False)]
    if not recommendations.empty:
        return recommendations[['title', 'director', 'listed_in', 'release_year', 'rating']].head(10)
    else:
        return "No movies found matching your preferences."
print("Welcome to the Movie Recommendation System!")
print("You can filter movies by Genre or Director (or both).")
user_genre = input("Enter your preferred genre (or press Enter to skip): ")
user_director = input("Enter your preferred director (or press Enter to skip): ")
recommendations = recommend_movies(genre=user_genre, director=user_director)
print("\nRecommended Movies:")
print(recommendations)
로그인 후 복사

Conclusion

My goals were achieved, and I had a great time taking on this challenge since it helped me realize that, even though learning is a process, there are days when I succeed and fail. This was definitely a success. Here, we celebrate victories as well as defeats since, in the end, each teach us something. Do let me know if you attempt this.
Till next time!

Note!!
The code is in my GitHub:
https://github.com/MichelleNjeri-scientist/Movie-Dataset-Exploration-and-Visualization

The Kaggle dataset is:
https://www.kaggle.com/datasets/shivamb/netflix-shows

위 내용은 영화 데이터 세트 탐색 및 시각화의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!