from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier(random_state=0) rf.fit(X_tr, y_tr) pred = rf.predict_proba(X_val) 촉박하게 공부하다 보니 평가지표에 대한 이해가 잘 되지 않는데요, 제출하는데는 크게 문제가 없는 것으로 보이는데 평가지표도 코드에 포함되어야 채점에 큰 문제가 없을..까요..?ㅠㅠ
age 컬럼에서 소수점인 칼럼을 찾기 위해 df[age] != round (df[age], 0)으로 수식 작성하셨는데요. 이렇게 될 경우, 36.3은 버림이 되면서 round 적용하기 전과, 적용한 이후가 같아져서 누락이 되는거 아닌지 궁금합니다. 영상에서는 36.3 값도 필터링이 되던데 어째서 가능한지 너무 궁금합니다ㅠ 바쁘신데 감사합니다!
문제1-2 유의확률(p-value)이 0.05 미만인 유의한 변수만을 사용해 다시 로지스틱 회귀 분석을 수행하시오. 이 회귀식의 유의한 회귀 계수(상수항 포함)의 합계를 구하시오. (반올림하여 소수 셋째 자리까지 계산) 여기서 상수함 포함 이라는 문구를 보면 어떻게 해설로 처리해야되는건가요? 그게 혹시 model.pvalues[1:] 이렇게 표현한게 상수함 포함을 얘기하는건가요?
기출문제 작업형2 공부하면서 라벨인코딩을을 하면 꼭 에러가 납니다. 같은 문제를 원-핫인코딩으로 해서 전후를 비교하면 데이터가 늘어난게 확인이 되는데 라벨인코딩은 에러가 나던지 데이터가 그대로 입니다.. 오타를 정확하게 확인했구요. 교재와도 정확하게 비교했는데 왜그럴까요?ㅜ 그리고 원-핫인코딩은 사전에 범주형,수치형데이터 분리없이 바로 사용해도 범주형데이터만 원-핫인코딩을 진행하는게 맞는거죠?
dqn 학습 부분에서, index에러가 자꾸 납니다.. dqn.py는 github에 올려져 있는 것을 그대로 사용했습니다. < 에러 코드 > (colab) C:\Users\pss60\Desktop\ML-Agents_Project\agents>python dqn.py Traceback (most recent call last): File "C:\Users\pss60\Desktop\ML-Agents_Project\agents\dqn.py", line 218, in <module> state = preprocess(dec.obs[OBS], dec.obs[GOAL_OBS]) IndexError: list index out of range < GridAgent > using System; using UnityEngine; using System.Linq; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using UnityEngine.Rendering; using UnityEngine.Serialization; using System.Collections.Generic; public class GridAgent : Agent { [FormerlySerializedAs("m_Area")] [Header("Specific to GridWorld")] public GridArea area; public float timeBetweenDecisionsAtInference; float m_TimeSinceDecision; [Tooltip("Because we want an observation right before making a decision, we can force " + "a camera to render before making a decision. Place the agentCam here if using " + "RenderTexture as observations.")] public Camera renderCamera; VectorSensorComponent m_GoalSensor; private Transform agentTrans = null; private Vector3 moveRight = new Vector3(1, 0, 0); private Vector3 moveLeft = new Vector3(-1, 0, 0); private Vector3 moveUp = new Vector3(0, 0, 1); private Vector3 moveDown = new Vector3(0, 0, -1); public enum GridGoal { GreenPlus, RedEx, } // Visual representations of the agent. Both are blue on top, but different colors on the bottom - this // allows the user to see which corresponds to the current goal, but it's not visible to the camera. // Only one is active at a time. public GameObject GreenBottom; public GameObject RedBottom; GridGoal m_CurrentGoal; public GridGoal CurrentGoal { get { return m_CurrentGoal; } set { switch (value) { case GridGoal.GreenPlus: GreenBottom.SetActive(true); RedBottom.SetActive(false); break; case GridGoal.RedEx: GreenBottom.SetActive(false); RedBottom.SetActive(true); break; } m_CurrentGoal = value; } } [Tooltip("Selecting will turn on action masking. Note that a model trained with action " + "masking turned on may not behave optimally when action masking is turned off.")] public bool maskActions = true; const int k_NoAction = 0; // do nothing! const int k_Up = 1; const int k_Down = 2; const int k_Left = 3; const int k_Right = 4; EnvironmentParameters m_ResetParams; public override void Initialize() { m_GoalSensor = this.GetComponent<VectorSensorComponent>(); m_ResetParams = Academy.Instance.EnvironmentParameters; } public override void CollectObservations(VectorSensor sensor) { Array values = Enum.GetValues(typeof(GridGoal)); int goalNum = (int)CurrentGoal; // 현재 에이전트의 x, y 좌표 위치 값을 관측 정보에 추가 sensor.AddObservation(agentTrans.position.x); sensor.AddObservation(agentTrans.position.z); // 각각 도형에 대한 좌표 위치 값을 관측 정보에 추가 List<int> otherPos = area.otherPos; for (int i = 0; i < otherPos.Count; i++) sensor.AddObservation(otherPos[i]); // 목표 지점에 대한 정보 m_GoalSensor.GetSensor().AddOneHotObservation(goalNum, values.Length); } public override void WriteDiscreteActionMask(IDiscreteActionMask actionMask) { // Mask the necessary actions if selected by the user. if (maskActions) { // Prevents the agent from picking an action that would make it collide with a wall var positionX = (int)agentTrans.localPosition.x; var positionZ = (int)agentTrans.localPosition.z; var maxPosition = (int)m_ResetParams.GetWithDefault("gridSize", 5f) - 1; if (positionX == 0) { actionMask.SetActionEnabled(0, k_Left, false); } if (positionX == maxPosition) { actionMask.SetActionEnabled(0, k_Right, false); } if (positionZ == 0) { actionMask.SetActionEnabled(0, k_Down, false); } if (positionZ == maxPosition) { actionMask.SetActionEnabled(0, k_Up, false); } } } // to be implemented by the developer public override void OnActionReceived(ActionBuffers actionBuffers) { // 매 행동마다 -0.01 보상(패널티) 부여 AddReward(-0.01f); var action = actionBuffers.DiscreteActions[0]; // 에이전트가 이동하게 될 위치 값을 저장할 변수 (Vector3) var targetPos = agentTrans.position; switch (action) { case k_NoAction: // do nothing break; case k_Right: // 부여받은 행동이 오른쪽이라면, targetPos = agentTrans.position + moveRight; // 현재 위치에서 1만큼 x축 방향으로 설정 break; case k_Left: targetPos = agentTrans.position + moveLeft; break; case k_Up: targetPos = agentTrans.position + moveUp; break; case k_Down: targetPos = agentTrans.position + moveDown; break; default: throw new ArgumentException("Invalid action value"); } var hit = Physics.OverlapBox( targetPos, new Vector3(0.3f, 0.3f, 0.3f)); // 벽에 부딪히지 않았다면, if (hit.Where(col => col.gameObject.CompareTag("wall")).ToArray().Length == 0) { // 정해진 위치로 이동 agentTrans.position = targetPos; // +오브젝트 만났다면, if (hit.Where(col => col.gameObject.CompareTag("plus")).ToArray().Length == 1) { ProvideReward(GridGoal.GreenPlus); EndEpisode(); } // x오브젝트 만났다면, else if (hit.Where(col => col.gameObject.CompareTag("ex")).ToArray().Length == 1) { ProvideReward(GridGoal.RedEx); EndEpisode(); } } } private void ProvideReward(GridGoal hitObject) { if (CurrentGoal == hitObject) { SetReward(1f); } else { SetReward(-1f); } } // WASD 키보드로 에이전트 이동 public override void Heuristic(in ActionBuffers actionsOut) { var discreteActionsOut = actionsOut.DiscreteActions; discreteActionsOut[0] = k_NoAction; if (Input.GetKey(KeyCode.D)) { discreteActionsOut[0] = k_Right; } if (Input.GetKey(KeyCode.W)) { discreteActionsOut[0] = k_Up; } if (Input.GetKey(KeyCode.A)) { discreteActionsOut[0] = k_Left; } if (Input.GetKey(KeyCode.S)) { discreteActionsOut[0] = k_Down; } } // to be implemented by the developer public override void OnEpisodeBegin() { area.AreaReset(); Array values = Enum.GetValues(typeof(GridGoal)); CurrentGoal = (GridGoal)values.GetValue(UnityEngine.Random.Range(0, values.Length)); } public void FixedUpdate() { WaitTimeInference(); } void WaitTimeInference() { if (renderCamera != null && SystemInfo.graphicsDeviceType != GraphicsDeviceType.Null) { renderCamera.Render(); } if (Academy.Instance.IsCommunicatorOn) { RequestDecision(); } else { if (m_TimeSinceDecision >= timeBetweenDecisionsAtInference) { m_TimeSinceDecision = 0f; RequestDecision(); } else { m_TimeSinceDecision += Time.fixedDeltaTime; } } } }
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 안녕하세요. 작년에 결제 후 6월 시험은 강의만 후루룩 듣고 시험 보러 가니 머리가 멍 해져서 제대로 시험도 못 치루고 나왔고 12월시험 준비는 교수님 책도 사고 그랬는데... 회사 내 근무지 이동과 출장기간과 겹쳐 시험을 보지 못했습니다...ㅠ 아직 많이 부족하여 혹시 다음 달 시험 보기 전까지만 연장이 가능한 방법이 있는지 여쭈어 봅니다. 혹시나 해서 메일 주소 남겨드립니다. subinsky@naver.co m 입니다.
train데이터에서 CLIENTNUM를 drop한 후 검증데이터분리를 하셨는데, drop을 하고 분리한뒤에 훈련을 시키면 나중에 어떻게 최종파일 값들과 CLIENTNUM이 매칭이 되는걸까요? CLIENTNUM값을 기준으로 데이터를 기억하고 훈련시키는건 아닌건지 ㅠ이해가 잘 안되서요
작업형2의 다중분류 같은 경우에는 평가 시 f1 = f1_score(y_val, pred, average='macro'를 입력해줘야 하는데 평가지표가 f1_score일때만 해당되나요? 만약 다중분류인데 평가 방법이 다른 방법이어도 똑같은 방식으로 뒤에 average='macro를 붙여주면 되는건가요?
1)혹시 현재 범주형 컬럼에 대해 라벨인코딩 한 후, 인코딩한 컬럼만 따로 학습에 사용하는 것이 아니라, 수치형 컬럼과 함께 전체 데이터(총 10개 컬럼)를 모델에 넣어 학습했습니다. 이때 오히려 성능이 더 잘 나왔는데, 이런 방식이 괜찮은지 확인 받고 싶습니다. from sklearn.preprocessing import LabelEncoder cols = list( train.select _dtypes(include = 'O')) for col in cols: le = LabelEncoder() train[col] = le.fit _transform(train[col]) test[col] = le.transform(test[col]) 이후 전체 데이터를 사용해 모델 학습을 진행했습니다. X_train, X_val, y_train, y_val = train_test_split(train.drop('성별',axis=1), train['성별'], test_size = 0.2, random_state = 0) print(X_train.shape, X_val.shape, y_train.shape, y_val.shape) #(2800, 10) (700, 10) (2800,) (700,) 범주형데이터 인코딩한 상태로 10개 컬럼 그대로 가지고 학습 from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import roc_auc_score rf = RandomForestClassifier(random_state = 0, max_depth =5) rf.fit (X_train,y_train) rf_predpro = rf.predict_proba(X_val) rf_rocauc = roc_auc_score(y_val,rf_predpro[:,1]) print(rf_rocauc) # train data 전체 데이터 사용 시 약 0.63, 범주형 컬럼 두 개만 썼을 때는 약 0.60 감사합니다
안녕하세요. 퇴근 후 딴짓 교재도 같이 공부를 하고 있습니다! 혹시 작업형2에서 연습문제에서 코딩을 할 때마다 ‘베이스라인’파트와 ‘심화’ 파트가 있는데 시험 볼 때 ‘베이스라인’과 ‘심화’파트 모두 제출해야 하나요..? ‘베이스라인’도 조금 벅차서 시험 볼 때 ‘베이스라인‘ 코드만 제출할 수 있나 해서요..
결측치 제거할 때 test는 처리하면 안된다고 하셨는데 다음과 같은 상황들에서 어떻게 처리해야 하나요? 1)train, test 둘다 결측치 있는 경우 train만 train = train.dropna()하면 되는지 2) train은 없고 test만 결측치가 있는경우 둘다 안 하면 되는지 3) train만 있고 test는 결측치가 없는 경우 train만 처리하면 되는지
강사님 풀이를 보면 수치형 데이터와 범주형 데이터를 분리해 전처리 한 후 다시 합치는 과정으로 진행하셨는데 저는 select.dtypes(inclde='object')와 select.dtypes(exclude='object')를 이용해 전처리 후 머신러닝을 진행하였습니다. roc_auc_score로 평가해보니 비슷하게 0.809가 나옵니다. 저는 수치형과 범주형을 따로 분리하고 전처리 하는게 헷갈려서 그런데 저처럼 과정을 진행해도 문제 없는거죠??
학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요! 질문과 관련된 영상 위치를 알려주면 더 빠르게 답변할 수 있어요 먼저 유사한 질문이 있었는지 검색해보세요 df.groupby(['부서','성과등급'])['근속연수'].transform('mean') 이라는 코드로 부서와 성과등급 기준 평균값을 구하신 부분에서 질문입니다. df.groupby(['부서','성과등급'])['근속연수'].mean() 위 코드와 같이 transform('mean')과 mean()이 어떤 차이점이 있는지 궁금해요.