오늘보다 더 나은 내일의 나에게_

비전공자의 IoT 국비 교육 수강일지 Day_89 본문

비전공자의 코딩일지

비전공자의 IoT 국비 교육 수강일지 Day_89

chan_96 2022. 4. 25. 17:01
728x90

안드로이드

프로젝트에서 파이어베이스 연결

Realtime Database
Connect to Firebase 클릭
Build  클릭
동의후 계속
프로젝트 만들기 클릭
연결 완료 후 모습
연결 완료 후 안드로이드 스튜디오 모습
Accept Changes 클릭
프로젝트 구성 모습
realtime database 클릭

규칙 탭에서 true로 설정
MainActivity에 아래 코드 추가 후 실행


build.gradle에서 버전 20.0.4로 변경 후 sync now 클릭

코드
더보기
MainActivity
package com.example.ex0425;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Write a message to the database
        // Connection conn = DriverManager.getConnection();
        FirebaseDatabase database = FirebaseDatabase.getInstance();

        // 데이터베이스 내 데이터를 접근하는 객체
        // 해당 참조경로가 없는 경우 -> 새롭게 생성
        // 참조경로가 있을 경우 -> 데이터를 접근 참조
        DatabaseReference myRef = database.getReference("message");

        // 데이터 저장
        //myRef.setValue("Hello, World!");
        myRef.setValue(new PersonVO("홍0동",25,true));

        // Read from the database
        // 데이터베이스 내 변경사항이 발생했을 때(이벤트)
        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                // getValue(클래스타입) -> 클래스타입에 맞춰 데이터를 읽어오는 메소드
                //String value = dataSnapshot.getValue(String.class);

                //객체데이터를 읽어올 때
                PersonVO value = dataSnapshot.getValue(PersonVO.class);

                Log.d(TAG, "Value is: " + value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
    }
}​


PersonVO

package com.example.ex0425;

public class PersonVO {

    private String name;
    private int age;
    private boolean gender;

    // 파이어베이스 데이터베이스에서 VO타입으로 읽어올 때
    // 기본생성자는 반드시! 정의가 되어있어야 읽어올 수 있다!
    public PersonVO(){}

    public PersonVO(String name, int age, boolean gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "PersonVO{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", gender=" + gender +
                '}';
    }
}​

 

실습


머신러닝

실습

0. 학습 데이터 전처리
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os # 파이썬을 이용해 시스템 정보를 확인하고 제어하는 라이브러리

# 특정 폴더 밑에 사진이름이 규칙적이지 않을 경우에는 os모듈을 이용하자
img = cv2.imread('./dog/2.png')
img.shape # => (224, 224, 3)


# 폴더 밑에 있는 파일이나 디렉토리 이름을 얻어내는 함수
dog_file_names = os.listdir('./dog')
dog_file_names

cat_file_names = os.listdir('./cat')
fox_file_names = os.listdir('./desert_fox')

dog_images = []
for fname in dog_file_names:
    raw_img = cv2.imread('./dog/'+fname)
    raw_img_rgb = cv2.cvtColor(raw_img,cv2.COLOR_BGR2RGB) #BGR -> RGB
    # 이미지 크기 조절하기
    resize_img = cv2.resize(raw_img_rgb, dsize=(224,224), interpolation=cv2.INTER_AREA)
    # 이미지 정규화(-1 ~ 1)
    normalized_img = (np.array(resize_img,dtype=np.float32) / 127.0) - 1
    dog_images.append(np.array(normalized_img)) # numpy타입으로 변환
    
dog_images = np.array(dog_images)
dog_images.shape #=> (371, 224, 224, 3)

cat_images = []
for fname in cat_file_names:
    raw_img = cv2.imread('./cat/'+fname)
    raw_img_rgb = cv2.cvtColor(raw_img,cv2.COLOR_BGR2RGB) #BGR -> RGB
    # 이미지 크기 조절하기
    resize_img = cv2.resize(raw_img_rgb, dsize=(224,224), interpolation=cv2.INTER_AREA)
    # 이미지 정규화(-1 ~ 1)
    normalized_img = (np.array(resize_img,dtype=np.float32) / 127.0) - 1
    cat_images.append(np.array(normalized_img)) # numpy타입으로 변환
    
cat_images = np.array(cat_images)
cat_images.shape

fox_images = []
for fname in fox_file_names:
    raw_img = cv2.imread('./desert_fox/'+fname)
    raw_img_rgb = cv2.cvtColor(raw_img,cv2.COLOR_BGR2RGB) #BGR -> RGB
    # 이미지 크기 조절하기
    resize_img = cv2.resize(raw_img_rgb, dsize=(224,224), interpolation=cv2.INTER_AREA)
    # 이미지 정규화(-1 ~ 1)
    normalized_img = (np.array(resize_img,dtype=np.float32) / 127.0) - 1
    fox_images.append(np.array(normalized_img)) # numpy타입으로 변환
    
fox_images = np.array(fox_images)
fox_images.shape

# 이미지 합치기
X = np.concatenate([dog_images,cat_images,fox_images])
X.shape # => (1145, 224, 224, 3)

# 개 0, 고양이 1, 사막여우 2
y = np.array([0] * 371 + [1] * 402 + [2] * 372)
y.shape # => (1145,)
dog_file_names 출력 결과
test 출력


1. 모델 생성
from tensorflow.keras.models import Sequential # 신경망을 붙이는 뼈대
from tensorflow.keras.layers import InputLayer, Dense # 입력층 / 중간및출력층

animal_model = Sequential() # 뼈대 생성
animal_model.add(InputLayer(input_shape=(224*224*3,))) #입력층
animal_model.add(Dense(units=128, activation='sigmoid')) #중간층
animal_model.add(Dense(units=128, activation='sigmoid')) #중간층
animal_model.add(Dense(units=64, activation='sigmoid')) #중간층
animal_model.add(Dense(units=32, activation='sigmoid')) #중간층
animal_model.add(Dense(units=3, activation='softmax')) #출력층


2. 모델 학습
animal_model.compile(loss='sparse_categorical_crossentropy',
                    optimizer='Adam',
                    metrics=['accuracy'])
                    
from sklearn.model_selection import train_test_split                    
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,
                                                random_state=425)                    

X_train.shape #=>(916, 224, 224, 3)
animal_model.fit(X_train.reshape(916,224*224*3),
                y_train, epochs=100)


3. 모델 예측
X_test.shape # => (229, 224, 224, 3)
pre = animal_model.predict(X_test.reshape(229,224*224*3))
pre
pre 출력


4. 모델 평가
from sklearn.metrics import classification_report
print(classification_report(y_test,pre.argmax(1)))
728x90
Comments