Exemple #1
0
def NRMSE(train=True):
    if train:
        # 학습 데이터 사용
        x = x_scaled_train
        y_true = y_train
    else:
        # 테스트 데이터 사용
        x = x_scaled_test
        y_true = y_test

    x = np.expand_dims(x, axis=0)
    n = x.shape[1]
    y_pred = load_model.predict(x)
    y_pred_rescale = y_scaler.inverse_transform(y_pred[0])

    RMSE = mean_squared_error(y_true, y_pred_rescale, squared=False)

    print("RMSE: ", RMSE)
    sum = 0
    for i in range(n):
        sum += y_true[i]

    #sum = 실제 관측값 평균
    sum /= n

    return 100 * RMSE / sum
Exemple #2
0
def plot_comparison(start_idx, length, train=True):
    if train:
        # 학습 데이터 사용
        x = x_scaled_train
        y_true = y_train
    else:
        # 테스트 데이터 사용
        x = x_scaled_test
        y_true = y_test

    end_idx = start_idx + length
    x = x[start_idx:end_idx]
    x = np.expand_dims(x, axis=0)
    y_true = y_true[start_idx:end_idx]

    y_pred = load_model.predict(x)
    y_pred_rescale = y_scaler.inverse_transform(y_pred[0])

    signal_pred = y_pred_rescale[:, 0]
    signal_true = y_true[:, 0]

    plt.figure(figsize=(21, 7))
    plt.plot(signal_true, label='true')
    plt.plot(signal_pred, label='pred')

    plt.ylabel('O3')
    plt.legend()
    plt.show()
Exemple #3
0
def ValuePredictor(to_predict_list, size):
    to_predict = np.array(to_predict_list).reshape(1, size)
    if (size == 8):  #Diabetes
        loaded_model = pickle.load(
            open('D:\AI\Project\End to end\Healthcare\Diabetes_model.pkl',
                 'rb'))
        result = loaded_model.predict(to_predict)
    if (size == 30):  #Cancer
        load_model = pickle.load(
            open('D:\AI\Project\End to end\Healthcare\Cancer_model.pkl', 'rb'))
        result = load_model.predict(to_predict)
    elif (size == 10):  #Liver
        loaded_model = pickle.load(
            open('D:\AI\Project\End to end\Healthcare\Liver_pickle.pkl', 'rb'))
        result = loaded_model.predict(to_predict)
    elif (size == 13):  #Heart
        loaded_model = pickle.load(
            open('D:\AI\Project\End to end\Healthcare\Heart_pickle.pkl', 'rb'))
        result = loaded_model.predict(to_predict)
    return result[0]
Exemple #4
0
with io.open(
        "/content/drive/MyDrive/Final Project/New_Project/model/LSTM/tokenizer.json",
        'w',
        encoding='utf-8') as f:
    f.write(json.dumps(tokenizer_json, ensure_ascii=False))
"""# Predict - LSTM"""

x_test

y_test

from tensorflow.keras.models import load_model

load_model = load_model('/content/best_LSTM_model.h5')

prediction = load_model.predict(X_test)

predictions = []
for i in tqdm(range(0, len(X_test))):
    predictions.append(np.argmax(prediction[i]))

y_test = pd.DataFrame(y_test)
y_test[0:1]

prediction = model.predict(X_test)

np.argmax(prediction[1])

y_test1 = y_test.reindex().label
y_test1
"""# Load_Model
img = img / 255.0

"""**reshape into a single sample with 3 channels**"""

img = img.reshape(1, 32, 32, 3)

"""**predict the class**"""

predictions = load_model.predict_classes(img)

predictions

labels =  ['airplane','automobile','bird','cat','deer','dog','frog','horse','ship','truck']

result = np.argmax(load_model.predict(img))
print(result)

labels[result]

"""**Test Image 2**"""

image_test= tf.keras.preprocessing.image.load_img('drive/My Drive/DATA files/CNN model weights/Deer.jpg', grayscale=False,
    color_mode='rgb')

img_test3 = tf.keras.preprocessing.image.load_img('drive/My Drive/DATA files/CNN model weights/Deer.jpg',
    grayscale=False,
    color_mode='rgb',
    target_size=(32,32))
img1 = np.array(img_test3)
img1.shape
Exemple #6
0
def predict_tomorrow():
    # 기상청 도시별 현재 날씨에서 수원의 기상 정보 받아옴
    wheather_source = requests.get(
        'https://www.weather.go.kr/weather/observation/currentweather.jsp')
    soup = BeautifulSoup(wheather_source.content, "html.parser")

    table = soup.find('table', {'class': 'table_develop3'})
    current_data = np.zeros([1, 7])
    flag = False
    for tr in table.find_all('tr'):
        tds = list(tr.find_all('td'))
        for td in tds:
            if td.find('a'):
                point = td.find('a').text
                if (point == '수원'):
                    current_data[0][0] = float(tds[5].text)  #현재 기온(°C)
                    current_data[0][1] = float(
                        re.findall("\d+\.\d+",
                                   tds[11].text.split('(')[1])[0])  #현재 풍속(m/s)
                    current_data[0][2] = float(tds[9].text)  #현재 습도(%)
                    flag = True
                    break
        if (flag):
            break

    # 공공데이터 포털의 한국환경공단_에어코리아_대기오염정보 api로 천천동 측정소의 대기 정보 받아옴
    M = '&returnType=xml&numOfRows=100&pageNo=1&stationName=%EC%B2%9C%EC%B2%9C%EB%8F%99&dataTerm=DAILY&ver=1.0'
    key = '0hZJZN2tb1cGI14XLG3tR7dATtivSKg9lF7f%2B58EEHvVnDGqxmxj5aXtarWm%2BNfKEPBxTMWKkduaYZLvdEBQOQ%3D%3D'
    url = 'http://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?serviceKey=' + key + M

    response = requests.get(url)
    soup2 = BeautifulSoup(response.content, "html.parser")

    cv = soup2.find('item')

    pm10 = soup2.find('pm10value').text
    pm25 = soup2.find('pm25value').text
    o3 = soup2.find('o3value').text
    no2 = soup2.find('no2value').text

    try:
        current_data[0][3] = float(pm10)  #현재 PM10(㎍/㎥)
        current_data[0][4] = float(pm25)  #현재 PM2.5(㎍/㎥)
        current_data[0][5] = float(o3)  #현재 오존농도(ppm)
        current_data[0][6] = float(no2)  #현재 이산화질소농도(ppm)
    except ValueError:
        print("현재 측정 값이 없습니다")
        return

    #print(current_data)

    # 현재 시간 + 24시간 뒤의 오존 농도 예측
    now = datetime.now()
    tomorrow = now + timedelta(days=1) + timedelta(hours=9)

    x_scaled_current = x_scaler.transform(current_data)
    c = np.expand_dims(x_scaled_current, axis=0)
    tomorrow_pred = load_model.predict(c)

    tomorrow_pred_rescale = y_scaler.inverse_transform(tomorrow_pred[0])
    O3_pred = float(str(tomorrow_pred_rescale[0])[2:-2])
    O3_pred = round(O3_pred, 3)
    year = tomorrow.year
    month = tomorrow.month
    day = tomorrow.day
    hour = tomorrow.hour

    print("수원시 장안구 천천동의 {0}년 {1}월 {2}일 {3}시 예상 오존 농도는 {4} ppm 입니다.".format(
        year, month, day, hour, O3_pred))
Exemple #7
0
font = cv2.FONT_HERSHEY_SIMPLEX
video_capture = cv2.VideoCapture(0)

while True:
    # Capture frame-by-frame
    ret, frame = video_capture.read()
    frame = imutils.resize(frame, width=1000)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray, 1.3, 5)
    EMOTIONS_LIST = [
        "Marah", "Jijik", "Takut", "Senang", "Netral", "Sedih", "Kaget"
    ]
    for (x, y, w, h) in faces:
        face_frame = gray[y:y + h, x:x + w]
        face_frame = cv2.resize(face_frame, (48, 48))
        preds = load_model.predict(face_frame[np.newaxis, :, :, np.newaxis])
        label = EMOTIONS_LIST[np.argmax(preds)]
        color = (0, 255, 0)
        cv2.putText(frame, label, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1,
                    color, 2)

        cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
        # Display the resulting frame
    cv2.imshow('Video', frame)
    # out.write(frame)

    if cv2.waitKey(33) & 0xFF == ord('q'):
        break

video_capture.release()
# out.release()