왕현성
코딩발자취
왕현성
전체 방문자
오늘
어제
  • 코딩 (277)
    • Python (71)
    • Java (16)
    • MySQL (34)
    • 인공지능 (48)
      • 머신러닝 (16)
      • 딥러닝 (32)
    • 영상처리 (4)
    • Rest API (21)
    • Android Studio (25)
    • streamlit (13)
    • DevOps (22)
      • AWS (9)
      • PuTTY (5)
      • Git (4)
      • Serverless (2)
      • Docker (2)
    • IT 기술 용어 (6)
    • 디버깅 ( 오류 해결 과정 ) (17)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

  • get_long_description
  • encoding='utf-8'
  • maskimage
  • 딥러닝
  • 영상기술
  • numpy
  • PYTHON
  • labelme
  • UnboundLocalError
  • alibi-detection
  • 컴퓨터비전
  • matplotlib
  • 영상처리역사
  • 의료이미징
  • pytorch
  • TensorFlow
  • 비지도학습
  • ComputerVision
  • 영상처리
  • 기상탐사
  • yolov8
  • alibidetect
  • unsupervised
  • tune()
  • PIL
  • OpenCV
  • labelme UnocodeDecodeError
  • pip install labelme
  • ckpt_file
  • imageprocessing

최근 댓글

최근 글

티스토리

250x250
hELLO · Designed By 정상우.
왕현성

코딩발자취

API서버 - 실시간 추천 기능 구현
Rest API

API서버 - 실시간 추천 기능 구현

2023. 1. 10. 10:02
728x90
  • 상관계수를 이용하여 상관계수가 높은 순으로 추천리스트 작성
  • 전체 기능에 대한 소스 코드 확인은 깃 허브에서 확인 가능합니다.


https://github.com/hyunsungKR/movie_api_server

 

GitHub - hyunsungKR/movie_api_server

Contribute to hyunsungKR/movie_api_server development by creating an account on GitHub.

github.com

이전 게시글에 있는 추천 기능은 파일을 주피터 노트북이나 구글코랩으로 미리 작업 후에 파일로 저장하고 그 파일을 가져와서 추천을 했다면 , 이번엔 DB에서 데이터를 비쥬얼스튜디오 코드로 가져와서 가공을 하고 추천을 할 수 있도록 개발을 해보았다.

class MovieRecommendRealTimeResource(Resource) :

    @jwt_required()
    def get(self) :

        user_id=get_jwt_identity()
        number=int(request.args.get('number'))

        try :
            connection = get_connection()
            query = '''select m.title, r.user_id, r.rating
                    from movie m
                    left join rating r
                    on m.id = r.movie_id;'''
            cursor = connection.cursor(dictionary=True)
            cursor.execute(query)
            result_list = cursor.fetchall()

            df = pd.DataFrame(data=result_list)
            df=df.pivot_table(index='user_id',columns='title',values='rating')


            movie_correlations = df.corr(min_periods=50)

            # 내 별점 정보를 가져와야 나의 맞춤형 추천 가능
            query = '''select m.title,r.rating
                    from rating r
                    left join movie m
                    on m.id = r.movie_id
                    where r.user_id = %s;'''
            record = (user_id,)

            cursor = connection.cursor(dictionary=True)
            cursor.execute(query,record)
            result_list = cursor.fetchall()

            print(result_list)

            cursor.close()
            connection.close()

        except Error as e :
            print(e)
            cursor.close()
            connection.close()
            return{"result":"fail","error":str(e)}, 500
        
        #  DB로부터 가져온 내 별점 정보를 
        #    데이터 프레임으로 만들어준다.
        my_rating=pd.DataFrame(data=result_list)
        
        
        #  내 별점 정보 기반으로 추천영화 목록을 만든다.
        similar_movies_list = pd.DataFrame()
        for i in range(my_rating.shape[0]):
            movie_title=my_rating['title'][i]
            similar_movie=movie_correlations[movie_title].dropna().sort_values(ascending=False).to_frame()
            similar_movie.columns = ['Correlation']
            similar_movie['weight']=my_rating['rating'][i] * similar_movie['Correlation']
            similar_movies_list=similar_movies_list.append(similar_movie)

        #  내가 본 영화 제거
        drop_index_list=my_rating['title'].to_list()
        for name in drop_index_list :
            if name in similar_movies_list.index :
                similar_movies_list.drop(name,axis=0,inplace=True)
        
        #  중복 추천된 영화는 weight값이 가장 큰 값으로만
        #    중복 제거한다.

        recomm_movie_list=similar_movies_list.groupby('title')['weight'].max().sort_values(ascending=False).head(number)

        


    

        #  JSON으로 클라이언트에 보내야한다.
        recomm_movie_list=recomm_movie_list.to_frame()
        recomm_movie_list=recomm_movie_list.reset_index()
        recomm_movie_list=recomm_movie_list.to_dict('records')

        
        
        return {'result':'success','itmes':recomm_movie_list,'count':len(recomm_movie_list)},200

포스트맨 테스트 결과

'Rest API' 카테고리의 다른 글

AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발  (0) 2023.01.12
API 서버 - 로그인한 회원과 비회원 구분하여 시스템 개발하기 // jwt_required(optional= )  (0) 2023.01.10
API 서버 - 구글 코랩으로 추천기능 개발 이후 영화 추천하는 API 개발 ( 배포 )  (0) 2023.01.09
API 서버 - query string 페이징 처리  (0) 2023.01.06
API서버 - 로그아웃 기능 구현하기 (jwt 토큰 파괴)  (0) 2023.01.05
    'Rest API' 카테고리의 다른 글
    • AmazonRekognition을 사용하여 객체탐지(Object detection) API 개발
    • API 서버 - 로그인한 회원과 비회원 구분하여 시스템 개발하기 // jwt_required(optional= )
    • API 서버 - 구글 코랩으로 추천기능 개발 이후 영화 추천하는 API 개발 ( 배포 )
    • API 서버 - query string 페이징 처리
    왕현성
    왕현성
    AI 머신비전 학습일지

    티스토리툴바